Bash – How to assign space-containing values to variables in bash using eval

bashquotingshell

I want to dynamically assign values to variables using eval.
The following dummy example works:

var_name="fruit"
var_value="orange"
eval $(echo $var_name=$var_value)
echo $fruit
orange

However, when the variable value contains spaces, eval returns an error, even if $var_value is put between double quotes:

var_name="fruit"
var_value="blue orange"
eval $(echo $var_name="$var_value")
bash: orange : command not found

Any way to circumvent this ?

Best Answer

Don't use eval, use declare

$ declare "$var_name=$var_value"
$ echo "fruit: >$fruit<"
fruit: >blue orange<
Related Question