BASH
Safely Source Environment Variables from a .env File
Load configuration from .env files into your Bash scripts. This snippet parses key-value pairs, handles comments, and quotes, making environment management simple.
#!/bin/bash
# Script to demonstrate sourcing environment variables from a .env file
# Default .env file path. Can be overridden.
ENV_FILE=".env"
# Function to load environment variables from a .env file
load_env() {
local env_path="$1"
if [ -z "$env_path" ]; then
env_path="$ENV_FILE"
fi
if [ ! -f "$env_path" ]; then
echo "Error: .env file not found at $env_path" >&2
return 1
fi
echo "Loading environment variables from $env_path..."
while IFS='=' read -r key value; do
# Skip comments and empty lines
if [[ -z "$key" || "$key" =~ ^# ]]; then
continue
fi
# Remove leading/trailing whitespace from key and value
key=$(echo "$key" | xargs)
value=$(echo "$value" | xargs)
# Remove quotes from value (single or double) if they exist
if [[ "$value" =~ ^["'].*["']$ ]]; then
value="${value:1:-1}"
fi
# Export the variable into the current shell's environment
export "$key"="$value"
echo " Loaded: $key"
done < "$env_path"
echo "Environment variables loaded."
return 0
}
# Create a dummy .env file for demonstration
cat > "$ENV_FILE" << EOF
# This is a comment
DATABASE_HOST=localhost
DATABASE_PORT=5432
API_KEY="your_api_key_123"
SECRET_PHRASE='a long phrase with spaces'
APP_ENV=development
EOF
# --- Main Script Logic ---
if load_env "$ENV_FILE"; then
echo "
Accessing loaded variables:"
echo "DATABASE_HOST: $DATABASE_HOST"
echo "DATABASE_PORT: $DATABASE_PORT"
echo "API_KEY: $API_KEY"
echo "SECRET_PHRASE: $SECRET_PHRASE"
echo "APP_ENV: $APP_ENV"
echo "
Attempting to access a non-existent variable (will be empty):"
echo "NON_EXISTENT_VAR: $NON_EXISTENT_VAR"
else
echo "Failed to load environment variables. Exiting." >&2
exit 1
fi
# Cleanup dummy .env file
rm "$ENV_FILE"
How it works: This script provides a robust function, `load_env`, to parse and export key-value pairs from a `.env` file into the current shell environment. It intelligently skips comments and empty lines, trims whitespace, and handles values enclosed in single or double quotes. This functionality is crucial for web developers to manage application configurations consistently across local development, testing, and CI/CD pipelines without hardcoding sensitive information.