BASH
Extracting and Exporting Environment Variables from .env
A bash script to parse a .env file, ignoring comments and empty lines, and export key-value pairs as environment variables for use in shell sessions or scripts.
#!/bin/bash
ENV_FILE=".env" # Path to your .env file
if [ ! -f "$ENV_FILE" ]; then
echo "Error: .env file not found at '$ENV_FILE'."
exit 1
fi
echo "--- Exporting variables from '$ENV_FILE' ---"
# Read the .env file line by line
while IFS= read -r line; do
# Skip empty lines and comments
[[ -z "$line" ]] || [[ "$line" =~ ^# ]] && continue
# Extract key and value
# Remove leading/trailing whitespace
# Remove quotes from value
key=$(echo "$line" | sed -E 's/^[[:space:]]*([^=]+)=.*$/\1/' | xargs)
value=$(echo "$line" | sed -E 's/^[^=]+=([[:space:]]*)(.*)/\2/' | xargs | sed -E 's/^"([^"]*)"$/\1/; s/^'\''([^'\']*)'\''$/\1/')
# Export the variable if key and value are not empty
if [[ -n "$key" && -n "$value" ]]; then
export "$key=$value"
echo "Exported: $key"
fi
done < "$ENV_FILE"
echo "----------------------------------------------"
echo "Variables exported. You can verify with: env | grep YOUR_VARIABLE"
echo "Note: This script exports variables to the current shell's sub-processes."
echo "To export to the current shell, use 'source ./your_script.sh' or '. ./your_script.sh'"
How it works: This script reads a `.env` file line by line, intelligently parsing each line to extract key-value pairs. It effectively skips empty lines and lines starting with `#` (comments). For each valid key-value pair, it uses `sed` and `xargs` to robustly extract the key and value, handling whitespace and stripping single or double quotes from the value. Finally, it uses the `export` command to make these variables available in the current shell's environment or any sub-processes launched from it. A note reminds the user to `source` the script if they want variables in the *current* shell session.