← Back to all snippets
BASH

Load Environment Variables from .env File

A Bash script to source and export variables from a .env file, making environment-specific configurations accessible in your shell or for specific commands.

#!/bin/bash

# Usage: source load_env.sh (to load into current shell)
# or: load_env.sh your_command (to run a command with loaded vars)

ENV_FILE=".env"

# Function to load variables
load_env_vars() {
    if [[ -f "$ENV_FILE" ]]; then
        echo "Loading environment variables from $ENV_FILE..."
        while IFS='=' read -r key value; do
            # Skip comments and empty lines
            if [[ -n "$key" && ! "$key" =~ ^# ]]; then
                # Remove leading/trailing quotes from value
                value=$(echo "$value" | sed -e 's/^"//' -e 's/"$//')
                value=$(echo "$value" | sed -e "s/^'//" -e "s/'$//")
                export "$key"="$value"
                echo "Exported: $key"
            fi
        done < "$ENV_FILE"
    else
        echo "Warning: $ENV_FILE not found. No environment variables loaded."
    fi
}

# If no arguments, load into current shell (intended for 'source')
if [[ $# -eq 0 && -z "$BASH_SOURCE" ]]; then
    echo "Please 'source' this script or provide a command to execute."
    echo "Example: source load_env.sh"
    echo "Example: ./load_env.sh npm run dev"
elif [[ $# -eq 0 ]]; then
    load_env_vars
else
    # If arguments are provided, load variables and then execute the command
    load_env_vars
    exec "$@"
fi
How it works: This Bash script provides a flexible way to load environment variables from a `.env` file. It reads each line, parsing key-value pairs and exporting them. It handles comments, empty lines, and removes quotes from values. You can either `source` the script to load variables into your current shell session, or execute it with a command (e.g., `./load_env.sh npm start`) to run that command with the variables pre-loaded. This is crucial for managing configurations in web projects, keeping sensitive data out of version control and easily switching between development and production settings.

Need help integrating this into your project?

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

Hire DigitalCodeLabs