BASH
Loading Environment Variables from .env File
A bash script to efficiently load key-value pairs from a .env file into the current shell's environment, streamlining application configuration.
#!/bin/bash
# Loads variables from a .env file into the current shell environment.
ENV_FILE=".env"
if [ -f "$ENV_FILE" ]; then
echo "Loading environment variables from $ENV_FILE..."
# Read each line, export key=value pairs
grep -v '^#' "$ENV_FILE" | while IFS='=' read -r key value; do
if [[ -n "$key" ]]; then # Ensure key is not empty
export "$key"="$value"
echo " - Exported $key"
fi
done
echo "Environment variables loaded."
else
echo "Error: .env file not found at $ENV_FILE"
exit 1
fi
# Example of how to use an exported variable (optional, for demonstration)
# echo "EXAMPLE_VAR is: $EXAMPLE_VAR"
How it works: This script reads a .env file, ignoring comments and empty lines. For each KEY=VALUE pair, it uses `export` to make the variable available in the current shell's environment. This is crucial for configuring web applications securely without hardcoding sensitive data, allowing easy switching between development, staging, and production environments.