BASH
Manage Environment Variables for Web Apps
A concise bash script to load environment variables from a `.env` file into the current shell session, crucial for configuring web applications securely.
#!/bin/bash
# This script loads environment variables from a .env file.
# Useful for local development or CI/CD pipelines.
ENV_FILE=".env"
if [ -f "$ENV_FILE" ]; then
echo "Loading environment variables from $ENV_FILE..."
# Read each line, export variables, ignoring comments and empty lines
while IFS='=' read -r key value; do
# Skip empty lines and comments
[[ -z "$key" ]] || [[ "$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."
else
echo "Warning: .env file not found at $ENV_FILE. No variables loaded." >&2
fi
# Example of accessing a loaded variable (if defined in .env)
# echo "DATABASE_URL: $DATABASE_URL"
How it works: This script provides a common method for managing environment variables in web development. It reads a `.env` file, parses each line to extract key-value pairs, and then uses the `export` command to make these variables available in the current shell session. It handles comments and ensures values are properly cleaned from whitespace or quotes, offering a simple yet effective way to configure web applications without hardcoding sensitive information directly into code.