I’m trying to load environment variables from a file.env in Bash
Difficulties arise if the file contains complex variables.
Exemple file.env (variable NODE)
# DB
; TEST
DB_USER=test
DB_HOST=localhost
DB_PORT=5432
DB_NAME=test
NODE ='{"node0001": "127.0.0.1","node0002": "127.0.0.2","node0003": "127.0.0.3"}'
# API
API_PORT=8081
API_LOG=True
; FUNC_DEBUG=True
I tried the command xargs
export $(cat file.env | sed 's/#.*//g' | xargs)
I found another implementation
export ENV_FILE="file.env"
if [ -f "$ENV_FILE" ]; then
echo "[INFO]: Reading $ENV_FILE file."
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 "[DONE]: Reading $ENV_FILE file."
else
echo "[ERROR]: $ENV_FILE not found."
fi
Both examples do not export variables very correctly.
I’m not good at bash, I don’t fully understand how to do it better.