BASH

Manage Environment Variables for Different Environments

Dynamically load environment variables from different .env files (e.g., .env.development, .env.production) using bash for consistent configuration across environments.

#!/bin/bash

# Usage: source ./load_env.sh [development|production|staging]

ENV_NAME=${1:-development} # Default to 'development' if no argument is provided
ENV_FILE=".env.$ENV_NAME"

if [ -f "$ENV_FILE" ]; then
    echo "Loading environment variables from $ENV_FILE"
    export $(grep -v '^#' $ENV_FILE | xargs)
    echo "Environment set to $ENV_NAME"
else
    echo "Warning: Environment file $ENV_FILE not found. Using default environment."
fi

# Example of using an environment variable after loading:
# echo "DATABASE_URL: $DATABASE_URL"

# To demonstrate, you can add this to your .bashrc or a startup script:
# source /path/to/this/script/load_env.sh production
How it works: This script provides a flexible way to load environment variables from different `.env` files based on the specified environment (e.g., development, production). It takes an optional argument for the environment name, defaults to 'development', and then sources the corresponding `.env.<env_name>` file. The `grep -v '^#'` and `xargs` command ensures comments are ignored and variables are exported correctly. This simplifies configuration management for web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs