← Back to all snippets
BASH

Securely Loading Environment Variables from a .env File

Learn how to load environment variables from a `.env` file into your Bash session, enabling secure configuration for web applications and scripts.

#!/bin/bash

# --- Configuration ---
ENV_FILE="./.env" # Path to your .env file

# Check if .env file exists
if [ ! -f "$ENV_FILE" ]; then
  echo "Error: .env file '$ENV_FILE' not found."
  echo "Please create it with key=value pairs, e.g., DB_HOST=localhost" 
  exit 1
fi

echo "Loading environment variables from $ENV_FILE..."

# Loop through each line in the .env file
while IFS='=' read -r key value || [ -n "$key" ]; do
  # Skip comments and empty lines
  [[ "$key" =~ ^#.* ]] && continue
  [[ -z "$key" ]] && continue

  # Remove leading/trailing whitespace and quotes from key and value
  key=$(echo "$key" | xargs)
  value=$(echo "$value" | xargs | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")

  # Export the variable
  export "$key"="$value"
  echo "  Exported $key"

done < "$ENV_FILE"

echo "Environment variables loaded."
echo "Example: Access a variable with 'echo \$DB_HOST' (after sourcing this script)"
# To make variables available in the current shell, source the script:
# source load_env.sh
How it works: This Bash script reads key-value pairs from a `.env` file and exports them as environment variables. It handles comments, empty lines, and removes quotes from values, making it robust for securely loading application configurations like database credentials or API keys without hardcoding them directly into scripts or source code. To make the variables available in the current shell, the script should be `source`d rather than executed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs