BASH

Load Environment Variables from File

A bash script to parse key-value pairs from a file (like .env) and export them as environment variables, enabling flexible and secure application configuration management.

#!/bin/bash

# Source environment variables from a .env file
# Usage: source ./load_env.sh

ENV_FILE=".env"

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

while IFS='=' read -r key value; do
  # Ignore comments and empty lines
  if [[ ! "$key" =~ ^# ]] && [[ -n "$key" ]]; then
    # Remove leading/trailing whitespace from key and value
    key=$(echo "$key" | xargs)
    value=$(echo "$value" | xargs)
    export "$key"="$value"
    # echo "Exported $key"
  fi
done < "$ENV_FILE"

# Example usage after sourcing:
# echo "DB_HOST: $DB_HOST"
# echo "APP_DEBUG: $APP_DEBUG"
How it works: This script reads an `.env` file line by line, parsing key-value pairs while ignoring comments and empty lines. It then exports these pairs as environment variables within the current shell session. This is crucial for securely managing application configurations, preventing sensitive data from being hardcoded, and allowing for flexible, environment-specific deployments without code changes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs