Environment File Loader Script
Bash script that safely loads environment variables from a .env file with validation and defaults.
#!/usr/bin/env bash
set -euo pipefail
ENV_FILE="${1:-.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Error: $ENV_FILE not found" >&2
exit 1
fi
while IFS= read -r line || [[ -n "$line" ]]; do
# Skip comments and empty lines
[[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
# Remove inline comments and trim whitespace
line="${line%%#*}"
line="$(echo "$line" | xargs)"
# Validate KEY=VALUE format
if [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then
export "$line"
else
echo "Warning: Skipping invalid line: $line" >&2
fi
done < "$ENV_FILE"
# Validate required variables
required_vars=("DATABASE_URL" "NODE_ENV" "PORT")
for var in "${required_vars[@]}"; do
if [[ -z "${!var:-}" ]]; then
echo "Error: Required variable $var is not set" >&2
exit 1
fi
done
echo "Loaded environment from $ENV_FILE"Use Cases
- Loading config before starting services
- CI/CD pipeline environment setup
- Shell script configuration management
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Nginx Reverse Proxy Configuration
Nginx config to reverse-proxy requests to a backend with WebSocket support and security headers.
Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.
Environment Variable Validation
Validate required environment variables at build time with type-safe access and descriptive errors.
Type-Safe Settings with Pydantic
Load and validate environment variables into a typed settings object using pydantic-settings with defaults.