#!/bin/bash # Function to load environment variables from a .env file load_dotenv() { local env_file="$1" if [[ ! -f "$env_file" ]]; then echo "Warning: .env file not found at '$env_file'" return 1 fi echo "Loading environment variables from $env_file..." # Read the .env file line by line 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) value=$(echo "$value" | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//") # Export the variable if [[ -n "$key" ]]; then export "$key=$value" # echo "Exported: $key=$value" # Uncomment for debugging fi done < "$env_file" echo "Environment variables loaded." } # Example usage: # Create a dummy .env file for demonstration cat << EOF > .env.example DB_HOST=localhost DB_PORT=5432 DB_USER="myuser" DB_PASSWORD='mypassword123' API_KEY=some_secret_key # This is a comment EMPTY_VAR= EOF load_dotenv ".env.example" echo "DB_HOST: $DB_HOST" echo "API_KEY: $API_KEY" echo "EMPTY_VAR: $EMPTY_VAR"