Skip to content

Instantly share code, notes, and snippets.

@jongan69
Created June 26, 2024 03:42
Show Gist options
  • Save jongan69/e6c32b701be809c31eefd239b99251a8 to your computer and use it in GitHub Desktop.
Save jongan69/e6c32b701be809c31eefd239b99251a8 to your computer and use it in GitHub Desktop.
To use this script: Make the script executable: bash Copy code chmod +x load_env.sh Run the script: bash Copy code source ./load_env.sh This script will read the .env file, export each variable to the current shell environment, and keep the shell open if running interactively. The source command is used to run the script in the current shell ses…
#!/bin/bash
# Function to export variables from .env file
export_env_vars() {
local env_file=$1
if [ ! -f "$env_file" ]; then
echo "The file $env_file does not exist."
return 1
fi
while IFS='=' read -r key value; do
if [[ ! "$key" =~ ^# && "$key" != "" ]]; then
export "$key"="$(echo "$value" | sed 's/^ *//;s/ *$//')"
fi
done < "$env_file"
}
# Source the .env file
export_env_vars ".env"
# Print a message indicating the variables have been set
echo "Environment variables from .env file have been exported."
# Keep the shell open if running interactively
if [[ $- == *i* ]]; then
exec "$SHELL"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment