Last active
February 4, 2025 14:40
-
-
Save shadiabuhilal/220aa09f9bb83caed93a1f87401fcc60 to your computer and use it in GitHub Desktop.
Load environment variables from dotenv / .env file in Bash script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script handles:
#
bash comment.'
from env var value."
from env var value.