Files
timebank-cc-public/scripts/load-env.sh
T

48 lines
1.7 KiB
Bash

#!/bin/bash
# Robust .env file loader for backup scripts
# This handles comments, quotes, and special characters properly
load_env() {
local env_file="$1"
if [ ! -f "$env_file" ]; then
return 1
fi
# Read .env file line by line and export valid variables
while IFS= read -r line; do
# Skip empty lines and comments
if [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]]; then
continue
fi
# Match valid environment variable pattern
if [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then
# Remove inline comments (everything after # that's not inside quotes)
local clean_line
if [[ "$line" =~ ^([^#]*[\"\']).*(#.*)$ ]]; then
# Line has quotes, need to be more careful with comment removal
clean_line="$line"
else
# Simple case, remove everything after #
clean_line="${line%%#*}"
fi
# Remove trailing whitespace
clean_line="${clean_line%"${clean_line##*[![:space:]]}"}"
# A quoted value: keep what is between the quotes (a password may hold # or spaces), drop the
# quotes and any comment after them. Without this the quotes became part of the value.
local key="${clean_line%%=*}" value="${clean_line#*=}"
if [[ "$value" =~ ^\"([^\"]*)\"([[:space:]]+#.*)?$ ]] || [[ "$value" =~ ^\'([^\']*)\'([[:space:]]+#.*)?$ ]]; then
clean_line="${key}=${BASH_REMATCH[1]}"
fi
# Export the variable
export "$clean_line"
fi
done < "$env_file"
return 0
}