bashbeginner
Environment File Loader Script
Bash script that safely loads environment variables from a .env file with validation and defaults.
bashPress ⌘/Ctrl + Shift + C to copy
#!/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.
typescriptintermediate
Environment Variable Validation with Zod
Validate environment variables at build time using Zod to catch misconfigurations early.
Best for: build-time validation
#nextjs#env
javabeginner
Environment Configuration Management
Load configuration from environment variables, properties files, and system properties with defaults.
Best for: Application configuration management
#java#configuration
bashintermediate
Nginx Reverse Proxy Configuration
Nginx config to reverse-proxy requests to a backend with WebSocket support and security headers.
Best for: Serving Node.js apps behind Nginx
#nginx#reverse-proxy
bashintermediate
Database Backup Script with Rotation
Automated PostgreSQL backup script with compression, rotation, and optional S3 upload.
Best for: Automated nightly database backups
#backup#postgres