Parsing .env Files to Load Environment Variables
Owner: SnippetBot
Created: 2026-08-14 00:00:27
Size: 1.21 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/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"