BASH
Managing Environment Variables for Deployments
Learn to set and manage application-specific environment variables using a bash script, ensuring consistent configurations across different deployment environments.
#!/bin/bash
# This script is intended to be sourced, not executed directly.
# Example: source ./env_config.sh
# --- Common Configuration (default values) ---
export APP_ENV="development"
export DEBUG_MODE="true"
export DATABASE_HOST="localhost"
export DATABASE_PORT="5432"
export API_BASE_URL="http://localhost:3000/api"
# --- Environment-Specific Overrides ---
# Check if a specific environment is requested via an argument
if [ "$1" = "production" ]; then
echo "Loading production environment configuration..."
export APP_ENV="production"
export DEBUG_MODE="false"
export DATABASE_HOST="prod_db.mycompany.com"
export DATABASE_PORT="5432"
export API_BASE_URL="https://api.mycompany.com/v1"
# Potentially load from a .env.production file
# if [ -f ".env.production" ]; then
# source .env.production
# fi
elif [ "$1" = "staging" ]; then
echo "Loading staging environment configuration..."
export APP_ENV="staging"
export DEBUG_MODE="true"
export DATABASE_HOST="staging_db.mycompany.com"
export DATABASE_PORT="5432"
export API_BASE_URL="https://staging-api.mycompany.com/v1"
# if [ -f ".env.staging" ]; then
# source .env.staging
# fi
else
echo "No specific environment provided or recognized. Loading development defaults."
fi
# Optional: Display loaded variables (for debugging)
echo "
--- Current Environment Variables ---"
env | grep -E '^(APP_ENV|DEBUG_MODE|DATABASE_HOST|DATABASE_PORT|API_BASE_URL)'
echo "-------------------------------------"
How it works: This bash script demonstrates a common pattern for managing application environment variables, crucial for different deployment stages (development, staging, production). It defines a set of default variables and then conditionally overrides them based on an argument passed to the script (e.g., `source env_config.sh production`). By using `export`, these variables become available to child processes or the current shell session when the script is 'sourced'. This ensures consistent and secure configuration without hardcoding sensitive values directly into application code, a best practice for web development.