← Back to all snippets
BASH

Load .env File into Current Shell

Learn how to easily load environment variables from a .env file into your current bash session, perfect for managing project configurations.

#!/bin/bash
# Usage: source load_env.sh .env

ENV_FILE=${1:-.env}

if [[ -f "$ENV_FILE" ]]; then
  echo "Loading environment variables from $ENV_FILE..."
  while IFS= read -r line; do
    # Skip comments and empty lines
    [[ "$line" =~ ^#.* ]] || [[ -z "$line" ]] && continue

    # Export key=value pairs
    export "$line"
  done < "$ENV_FILE"
  echo "Environment variables loaded."
else
  echo "Error: .env file not found at $ENV_FILE" >&2
  exit 1
fi
How it works: This script reads a specified `.env` file line by line. It skips comment lines (starting with `#`) and empty lines. For every valid `KEY=VALUE` line, it uses the `export` command to make that variable available in the current shell session. This is extremely useful for managing secrets and configuration without hardcoding them directly into scripts or source code. To use, you must `source` the script (e.g., `source load_env.sh`).

Need help integrating this into your project?

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

Hire DigitalCodeLabs