BASH

Load Project Environment Variables from .env File

Safely load environment variables from a .env file into the current shell session, crucial for local development and CI/CD pipelines in web projects.

#!/bin/bash
# Loads environment variables from a .env file into the current shell session.
# Usage: source load_env.sh

ENV_FILE=".env"

if [[ -f "$ENV_FILE" ]]; then
    echo "Loading environment variables from $ENV_FILE..."
    # Read the file line by line
    while IFS='=' read -r key value; do
        # Skip comments and empty lines
        if [[ ! "$key" =~ ^# ]] && [[ -n "$key" ]]; then
            # Remove leading/trailing whitespace and quotes from key and value
            key=$(echo "$key" | xargs)
            value=$(echo "$value" | xargs | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")
            
            # Export the variable
            export "$key"="$value"
            echo "Exported $key"
        fi
    done < "$ENV_FILE"
    echo "Environment variables loaded."
else
    echo "Warning: .env file not found at $ENV_FILE. Skipping environment variable loading."
fi
How it works: This script reads an `.env` file, parsing each `KEY=VALUE` line. It intelligently skips comments and empty lines, trims whitespace, removes quotes from values, and then `export`s each variable into the current shell environment. This is a robust and widely used pattern for managing configuration and sensitive information in web projects, ensuring consistency across development and deployment environments without hardcoding credentials.

Need help integrating this into your project?

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

Hire DigitalCodeLabs