#!/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:]]}"}" # Export the variable export "$clean_line" fi done < "$env_file" return 0 }