bashbeginner

Environment File Loader Script

Bash script that safely loads environment variables from a .env file with validation and defaults.

bash
#!/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.