← Back to all snippets
BASH

Loading Environment Variables from a .env File

Securely manage configuration in Bash scripts by loading environment variables from a `.env` file, preventing hardcoding sensitive data and improving portability.

#!/bin/bash

ENV_FILE=".env"

# Create a dummy .env file for demonstration
cat << EOF > "$ENV_FILE"
DB_HOST=localhost
DB_PORT=5432
DB_USER=myuser
DB_PASS=mYsEcReTpAsSwOrD
APP_DEBUG=true
# This is a comment
EMPTY_VAR=
SPACED_VAR="Value with spaces"
EOF
echo "Created dummy .env file: $ENV_FILE"

# Function to load environment variables from .env
load_env() {
    if [ -f "$1" ]; then
        echo "Loading environment variables from $1"
        while IFS='=' read -r key value; do
            # Skip comments and empty lines
            [[ "$key" =~ ^#.* ]] && continue
            [[ -z "$key" ]] && continue

            # Remove leading/trailing whitespace and quotes from value
            value=$(echo "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//')
            
            # Export the variable
            export "$key"="$value"
            echo "Exported $key" # For demonstration, remove in production
        done < "$1"
    else
        echo "Warning: .env file not found at $1"
    fi
}

# Call the function to load .env variables
load_env "$ENV_FILE"

echo -e "
--- Accessing Loaded Variables ---"
echo "Database Host: $DB_HOST"
echo "Database Port: $DB_PORT"
echo "Database User: $DB_USER"
echo "Database Pass: $DB_PASS"
echo "App Debug: $APP_DEBUG"
echo "Empty Var: '${EMPTY_VAR}'"
echo "Spaced Var: '${SPACED_VAR}'"

# Clean up dummy .env file
rm "$ENV_FILE"
How it works: This script demonstrates how to load environment variables from a `.env` file into a Bash session. The `load_env` function reads the `.env` file line by line, ignoring comments and empty lines. It parses key-value pairs, stripping whitespace and quotes from values, and then uses `export` to make these variables available to the current script and any child processes. This approach is essential for managing sensitive application configurations securely and efficiently without hardcoding them into scripts.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs