BASH

Load Environment Variables from .env Files

Discover how to securely load environment-specific variables from .env files into your bash scripts, preventing sensitive data from hardcoding.

#!/bin/bash

# Usage: source load_env.sh .env.development
# Or directly:
# . load_env.sh .env.production

ENV_FILE=$1

if [ -z "$ENV_FILE" ]; then
  echo "Usage: source $0 <env_file>"
  exit 1
fi

if [ ! -f "$ENV_FILE" ]; then
  echo "Error: Environment file '$ENV_FILE' not found."
  exit 1
fi

while IFS='=' read -r key value; do
  if [[ ! "$key" =~ ^# ]] && [[ -n "$key" ]]; then
    export "$key"="$value"
    # echo "Exported: $key=$value" # Uncomment for debugging
  fi
done < "$ENV_FILE"

# Example usage in the same script or after sourcing:
# echo "DATABASE_HOST: $DATABASE_HOST"
# echo "API_KEY: $API_KEY"
How it works: This script provides a common method to load environment variables from a `.env` file (e.g., `.env.development`, `.env.production`) into the current shell session. It parses each line, ignoring comments and empty lines, and exports key-value pairs. This is particularly useful for managing different configurations across development, staging, and production environments without hardcoding sensitive information directly into scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs