# Export all variables from a env var file # $1 => env var file path source_env_var_file() { file="$1" if [ ! -f "$file" ]; then echo "Error: $file does not exist" return 1 fi while IFS= read -r line; do # Trim whitespace from start and end of line line=$(echo "$line" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//') # Validate the line against the regex (skips empty lines and comments and lines where key is not valid) [[ ! "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*=.* ]] && continue # # Skip empty lines # [ -z "$line" ] && continue # # Skip comments # [[ "$line" =~ ^#.*$ ]] && continue # Split the line into a key and value key=$(echo "$line" | cut -d "=" -f 1) value=$(echo "$line" | cut -d "=" -f 2-) # Trim whitespace from start and end of value value=$(echo "$value" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//') # Skip if the key or value is empty [ -z "$key" ] || [ -z "$value" ] && continue # If the value isn't wrapped in quotes and contains any special characters, wrap it in single quotes if [[ "$value" != "'"* && "$value" != '"'* ]] && [[ "$value" =~ [[:space:]\!\@\#\$\%\^\&\*\(\)\[\]\{\}\<\>\?\!\~\`\:\;\+\=\-\.\/\\\|] ]]; then value="'$value'" fi # Export the variable export "$key"="$value" done <"$file" # # eval "$(grep -E '^export [A-Za-z_][A-Za-z0-9_]*=.*' "$file")" # validates lines with regex as (export key=value) and evals the line # eval "$(grep -E '^[A-Za-z_][A-Za-z0-9_]*=.*' "$file" | sed 's/.*/export &;/')" # normal approach - validate lines with regex as (key=value) and export them # Special chars to check: \s,!,@,#,$,%,^,&,*,(,),[,],{,},<,>,?,!,~,`,",',:,;,+,=,-,.,_,/,\,| # Wrap the value in single quotes if contains special chars and not already wrapped # eval "$(grep -E '^[A-Za-z_][A-Za-z0-9_]*=.*' "$file" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//; s/[^A-Za-z0-9_]=/=/; s/.*/&;/; s/=[^'"'"'A-Za-z0-9_]/='\''&'\''/')" }