BASH

Load .env File Variables into Current Bash Session

Easily manage configuration by loading environment variables from a .env file directly into your current Bash shell, simplifying local web development setups.

#!/bin/bash

# --- Configuration ---
ENV_FILE=".env"

# --- Script Logic ---
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at $ENV_FILE"
    return 1 # Use 'return' for sourcing, 'exit' for executing
fi

while IFS= read -r line || [[ -n "$line" ]]; do
    # Skip comments and empty lines
    [[ "$line" =~ ^#.*$ ]] && continue
    [[ -z "$line" ]] && continue

    # Export key-value pairs
    if [[ "$line" =~ ^([A-Za-z_]+[A-Za-z0-9_]*)=(.*)$ ]]; then
        KEY="${BASH_REMATCH[1]}"
        VALUE="${BASH_REMATCH[2]}"

        # Remove leading/trailing quotes if present
        VALUE=$(echo "$VALUE" | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")

        export "$KEY"="$VALUE"
        echo "Exported: $KEY"
    fi
done < "$ENV_FILE"

echo ".env variables loaded."
How it works: This script reads a `.env` file line by line, intelligently parsing key-value pairs while ignoring comments and empty lines. It then exports these as environment variables into the *current* Bash session. This is a crucial utility for web developers to manage project configurations and sensitive data during local development, ensuring variables are accessible to subsequent commands without manual entry. **Important:** To apply these variables to your current shell, you must `source` the script (e.g., `source load-env.sh`) rather than just executing it.

Need help integrating this into your project?

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

Hire DigitalCodeLabs