Skip to content

Instantly share code, notes, and snippets.

@shadiabuhilal
Last active March 18, 2024 10:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadiabuhilal/220aa09f9bb83caed93a1f87401fcc60 to your computer and use it in GitHub Desktop.
Save shadiabuhilal/220aa09f9bb83caed93a1f87401fcc60 to your computer and use it in GitHub Desktop.
Load environment variables from dotenv / .env file in Bash script
#!/bin/bash
# Specify the path to your .env file
ENV_FILE=".env"
# Function to success color text with green
successText() {
tput setaf 2
echo "$@"
tput sgr0
}
# Function to info color text with blue
infoText() {
tput setaf 4
echo "$@"
tput sgr0
}
# Function to error color text with red
errorText() {
tput setaf 1
echo "$@"
tput sgr0
}
# Check if the .env file exists
if [ -f "$ENV_FILE" ]; then
echo $(infoText "[INFO]: Reading $ENV_FILE file.")
# Read the .env file line by line
while IFS= read -r line; do
# Skip comments and empty lines
if [[ "$line" =~ ^\s*#.*$ || -z "$line" ]]; then
continue
fi
# Split the line into key and value
key=$(echo "$line" | cut -d '=' -f 1)
value=$(echo "$line" | cut -d '=' -f 2-)
# Remove single quotes, double quotes, and leading/trailing spaces from the value
value=$(echo "$value" | sed -e "s/^'//" -e "s/'$//" -e 's/^"//' -e 's/"$//' -e 's/^[ \t]*//;s/[ \t]*$//')
# Export the key and value as environment variables
export "$key=$value"
done < "$ENV_FILE"
echo $(successText "[DONE]: Reading $ENV_FILE file.")
else
echo $(errorText "[ERROR]: $ENV_FILE not found.")
fi
@shadiabuhilal
Copy link
Author

This script handles:

  • Ignoring # bash comment.
  • Remove ' from env var value.
  • Remove " from env var value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment