BASH

Load Configuration from Environment Variables with Defaults

Securely manage application configuration in bash scripts. This snippet loads settings from environment variables, providing default values for flexibility.

#!/bin/bash

# --- Configuration Variables ---
# Each variable attempts to read from an environment variable first,
# then falls back to a default value if the environment variable is not set.

# Database Host
# Example: export DB_HOST="prod.database.com"
DB_HOST=${DB_HOST:-"localhost"}

# Database Port
# Example: export DB_PORT="5432"
DB_PORT=${DB_PORT:-"3306"} # Default for MySQL

# Database Name
# Example: export DB_NAME="my_production_db"
DB_NAME=${DB_NAME:-"default_app_db"}

# Application Environment
# Example: export APP_ENV="production"
APP_ENV=${APP_ENV:-"development"}

# API Key (Sensitive - use secure methods in production)
# Example: export MY_API_KEY="super_secret_key"
MY_API_KEY=${MY_API_KEY:-"fallback_api_key_for_dev"}

# Debug Mode
# Example: export DEBUG_MODE="true"
DEBUG_MODE=${DEBUG_MODE:-"false"}


# --- Display Loaded Configuration ---
echo "--- Application Configuration ---"
echo "Database Host: $DB_HOST"
echo "Database Port: $DB_PORT"
echo "Database Name: $DB_NAME"
echo "App Environment: $APP_ENV"
echo "API Key: $([[ "$MY_API_KEY" != "fallback_api_key_for_dev" ]] && echo "********" || echo "Using fallback key")" # Mask sensitive info
echo "Debug Mode: $DEBUG_MODE"
echo "---------------------------------"

# --- Script Logic based on Config ---
if [ "$APP_ENV" = "production" ]; then
    echo "Running in PRODUCTION environment."
    # Add production-specific logic here (e.g., specific logging, disable debug)
    DEBUG_MODE="false" # Ensure debug is off in production
else
    echo "Running in $APP_ENV environment."
    if [ "$DEBUG_MODE" = "true" ]; then
        echo "Debug mode is ON."
    fi
fi

# Example of using a config value
echo "Connecting to database at $DB_HOST:$DB_PORT/$DB_NAME..."
# Placeholder for actual connection logic
How it works: This bash snippet demonstrates a best practice for managing configuration in scripts: loading values from environment variables with sensible defaults. Using the `variable_name=${VARIABLE_NAME:-"default_value"}` syntax, it prioritizes externally provided environment variables (e.g., `DB_HOST`) over hardcoded defaults. This approach is fundamental for building 12-factor compliant applications, enabling easy configuration changes without modifying the script, perfect for containerized deployments and different development, staging, or production environments.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs