BASH
Load Environment Variables from .env File in Bash
Learn how to load environment variables from a .env file into your Bash script for dynamic configuration, commonly used in web development projects.
#!/bin/bash
# Source .env file if it exists
if [ -f ".env" ]; then
echo "Loading environment variables from .env"
export $(grep -v '^#' .env | xargs)
else
echo ".env file not found, proceeding without it."
fi
# Example usage of a loaded variable
# echo "DATABASE_URL: $DATABASE_URL"
How it works: This script checks for the presence of a `.env` file in the current directory. If found, it reads each non-commented line (lines not starting with `#`), extracts key-value pairs, and exports them as environment variables using `export $(...)`. This makes the variables accessible to the current shell session or subsequent commands within the script, providing dynamic configuration for web projects.