BASH
Load .env File into Current Shell Environment
A simple Bash snippet to parse and load key-value pairs from a .env file into the current shell's environment variables, essential for local development.
#!/bin/bash
ENV_FILE=".env"
if [ -f "$ENV_FILE" ]; then
echo "Loading environment variables from $ENV_FILE"
while IFS='=' read -r key value
do
# Skip empty lines and comments
[[ "$key" =~ ^#.* ]] && continue
[[ -z "$key" ]] && continue
# Remove leading/trailing whitespace and quotes from value
value=$(echo "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")
export "$key"="$value"
echo "Exported $key"
done < "$ENV_FILE"
else
echo "Error: $ENV_FILE not found."
exit 1
fi
# Example usage: echo $DB_HOST
How it works: This script reads a `.env` file line by line. For each valid key-value pair, it removes comments, handles potential quotes, and then `export`s the variable into the current shell environment. This is crucial for web developers working with applications that rely on environment variables (like Node.js, Python, PHP frameworks) to manage sensitive data or configuration differences between environments. To use it, `source ./your-script.sh` so variables are exported to the current shell.