BASH

Load and Export .env Variables in Bash

A bash script to parse a `.env` file and export its key-value pairs as environment variables, commonly used for web application configuration.

#!/bin/bash
# Usage: source load_env.sh /path/to/.env

ENV_FILE=${1:-.env}

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

echo "Loading environment variables from $ENV_FILE..."

# Read each line, ignore comments and empty lines
while IFS='=' read -r key value; do
  if [[ ! -z "$key" && "$key" != \#* ]]; then
    # Remove surrounding quotes from value, if any
    value=$(echo "$value" | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")
    export "$key"="$value"
    echo "Exported $key"
  fi
done < "$ENV_FILE"

# Example usage after sourcing:
# echo "DB_HOST: $DB_HOST"
How it works: This script reads a `.env` file line by line, parsing key-value pairs. It skips comments and empty lines, then removes potential quotes from the value before exporting each as an environment variable. This is crucial for web applications that rely on `.env` files for configuration, allowing scripts or application processes to access these variables. It should be `source`d (or `.`'d) to apply variables to the current shell.

Need help integrating this into your project?

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

Hire DigitalCodeLabs