BASH

Manage Project-Specific Environment Variables

Learn to load and export project-specific environment variables from a `.env` file into your current shell session, essential for managing configurations in development.

#!/bin/bash

# Usage: source setup_env.sh or . setup_env.sh
# This script should be sourced, not executed directly, to affect the current shell.

ENV_FILE=".env" # Default environment file name

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

    # Remove leading/trailing whitespace and quotes from value
    value=$(echo "$value" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//")

    # Export the variable
    export "$key"="$value"
    echo "Exported: $key"
  done < "$ENV_FILE"
  echo "Environment variables loaded."
else
  echo "Error: .env file not found at $(pwd)/$ENV_FILE"
  echo "Please create one with key=value pairs."
  # Optionally, exit or handle the error differently
  # exit 1
fi

# Example of how to use it after sourcing:
# echo "DATABASE_URL: $DATABASE_URL"
# echo "API_KEY: $API_KEY"
How it works: This script allows you to load and export environment variables defined in a `.env` file into your current shell session. By sourcing it (`. ./setup_env.sh`), it parses `key=value` pairs, handles comments and quotes, and makes them available to subsequent commands, perfect for managing project configurations without hardcoding.

Need help integrating this into your project?

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

Hire DigitalCodeLabs