BASH
Load and Use Environment Variables for Application
A bash script demonstrating how to load environment variables from a `.env` file and make them available to a child process or script, crucial for secure configuration management in web projects.
#!/bin/bash
# Path to your .env file (relative or absolute)
ENV_FILE="./.env"
# Check if .env file exists
if [ ! -f "$ENV_FILE" ]; then
echo "Error: .env file not found at $ENV_FILE. Please create it."
exit 1
fi
echo "Loading environment variables from $ENV_FILE..."
# Method 1: Source the .env file directly (recommended for simple cases)
# This makes variables available to the current shell and child processes.
# NOTE: This works best if .env contains 'KEY=VALUE' format, not 'export KEY=VALUE'
set -a # Automatically export all variables that are set or modified
source "$ENV_FILE"
set +a # Turn off auto-export
# Verify variables (for demonstration purposes)
echo "
Loaded Variables (for demonstration):"
echo "DB_HOST: ${DB_HOST:-<not set>}"
echo "DB_USER: ${DB_USER:-<not set>}"
echo "API_KEY: ${API_KEY:-<not set>}"
# Now you can run your application or script that uses these variables.
# Example: node app.js, python my_script.py, php artisan serve, etc.
# echo "
Running application with loaded environment variables..."
# /path/to/your/application_command
# Example: Running a simple Python script that prints environment variables
# python -c 'import os; print(f"Python sees DB_HOST: {os.environ.get("DB_HOST")}")'
How it works: This script illustrates a robust way to load configuration from a `.env` file into your shell environment, making variables accessible to subsequent commands or applications. It checks for the file's existence, then uses `set -a` and `source` to automatically export all variables defined within it. This is a secure and standard practice for managing sensitive credentials (like database passwords or API keys) and application settings in web development without hardcoding them directly into the application's source code, promoting better security and portability.