I'm parsing a file with key=value
data and then export them as environment variables. My solution works, but not with special characters, example:
.data
VAR1=abc
VAR2=d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^
script.sh
#!/bin/bash
while IFS="=" read -r key value; do
case "$key" in
'#'*) ;;
*)
eval "$key=\"$value\""
export $key
esac
done < .data
$ . ./script.sh
Output:
$ echo $VAR1
abc
$ echo $VAR2
d#r3_P{os-!kblg1=mf6@3l^
but should be: d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^
Except within single quotes, characters with special meanings in Bash have to be escaped to preserve their literal values. In practice, this is mainly done with the escape character \ <backslash>.
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
In a shell, the most common way to escape special characters is to use a backslash before the characters. These special characters include characters like ?, +, $, !, and [. The other characters like ?, !, and $ have special meaning in the shell as well.
Just escape the $ sign with backslash \
Just use single quotes:
export VAR2='d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^'
You don't need eval at all, just use declare
built-in in bash
to create variables on-the-fly!
case "$key" in
'#'*) ;;
*)
declare $key=$value
export "$key"
esac
I found the following script (to be sourced) helpful:
set -a
source <(cat development.env | \
sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
set +a
From: https://stackoverflow.com/a/66118031/339144
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With