BASH

Manage App Environment Variables with .env

Learn to load and manage application configuration using a `.env` file in Bash, ensuring sensitive data and settings are handled securely.

#!/bin/bash

# Configuration
ENV_FILE="./.env"

# Check if .env file exists
if [ -f "$ENV_FILE" ]; then
    echo "Loading environment variables from $ENV_FILE..."
    # Read each line, export variables
    while IFS='=' read -r key value; do
        # Skip comments and empty lines
        if [[ "$key" =~ ^#.* ]] || [[ -z "$key" ]]; then
            continue
        fi
        # Trim whitespace from key and value
        key=$(echo "$key" | xargs)
        value=$(echo "$value" | xargs)

        # Export the variable
        export "$key"="$value"
        echo "  Exported: $key"
    done < "$ENV_FILE"
    echo "Environment variables loaded."
else
    echo "Warning: .env file not found at $ENV_FILE. Proceeding without loading environment variables."
fi

# Example of using an environment variable
# echo "My API Key: $MY_API_KEY"
# echo "Database Host: $DB_HOST"

# Your application logic here, which can now access these variables
# For instance, starting a Node.js app:
# node app.js

# To verify a variable, uncomment:
# echo "API_KEY (from env): $API_KEY"
How it works: This script provides a simple way to load environment variables from a `.env` file into the current shell session. It parses each line, ignoring comments and empty lines, and then uses the `export` command to make the key-value pairs available as environment variables. This is crucial for managing application configurations, especially sensitive data like API keys or database credentials, without hardcoding them directly into scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs