BASH
Loading Environment Variables from .env Files
Learn how to securely manage application configuration by loading environment variables from a .env file into your bash script or current shell session.
#!/bin/bash
# Path to your .env file relative to the script
ENV_FILE=".env"
# Check if the .env file exists
if [ -f "$ENV_FILE" ]; then
echo "Loading environment variables from $ENV_FILE..."
# Read each line, filter out comments and empty lines, and export variables
# The 'eval' command is used carefully here as the source of variables is controlled
# An alternative without eval is 'export $(grep -v '^#' "$ENV_FILE" | xargs)'
# but using a loop is safer for complex values and allows for feedback.
while IFS='=' read -r key value; do
# Skip empty lines and comments
[[ -z "$key" ]] || [[ "${key:0:1}" == "#" ]] && continue
# Remove potential quotes from value (simple case)
value=$(echo "$value" | sed -e 's/^"//' -e 's/"$//')
# Export the variable
export "$key"="$value"
echo " Exported: $key"
done < "$ENV_FILE"
else
echo "Warning: .env file not found at $ENV_FILE. No environment variables loaded."
fi
# Example of using loaded variables
echo "
--- Using loaded variables ---"
if [ -n "$DB_HOST" ]; then
echo "Database Host: $DB_HOST"
fi
if [ -n "$API_KEY" ]; then
echo "API Key (first 5 chars): ${API_KEY:0:5}..."
fi
if [ -n "$APP_ENV" ]; then
echo "Application Environment: $APP_ENV"
fi
# To demonstrate, create a .env file like this in the same directory:
# DB_HOST=localhost
# DB_PORT=5432
# API_KEY="your_secret_api_key_12345"
# APP_ENV=development
# # This is a comment
How it works: This script provides a robust way to load configuration from a `.env` file, a common practice in modern web development. It reads each line from the specified `.env` file, skips comments and empty lines, and then exports key-value pairs as environment variables. This allows developers to easily manage environment-specific settings (like database credentials or API keys) outside of their main codebase, promoting security and flexibility across different deployment environments.