BASH

Managing Project-Specific Environment Variables

Load project-specific environment variables from a .env file into your Bash session or scripts, ensuring consistent configurations across different development environments.

#!/bin/bash
# Script to load environment variables from a .env file

ENV_FILE=".env"

if [ -f "$ENV_FILE" ]; then
    echo "Loading environment variables from $ENV_FILE..."
    export $(grep -v '^#' "$ENV_FILE" | xargs -0)
    echo "Variables loaded."
else
    echo "Error: .env file not found at $ENV_FILE"
    exit 1
fi

# Example usage of a loaded variable (if defined in .env)
# echo "API_KEY is: $API_KEY"
How it works: This script checks for the existence of a `.env` file. If found, it reads each non-commented line, exports the key-value pairs as environment variables into the current shell session, making them accessible to subsequent commands or scripts. The `xargs -0` ensures proper handling of spaces or special characters in variable values.

Need help integrating this into your project?

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

Hire DigitalCodeLabs