A good way to work with
eval is to replace it with
echo for testing.
eval work the same (if we set aside the
\x expansion done by some
echo implementations like
bash's under some conditions).
Both commands join their arguments with one space in between. The difference is that
echo displays the result while
eval evaluates/interprets as shell code the result.
So, to see what shell code
eval $(echo $var_name=$var_value)
would evaluate, you can run:
$ echo $(echo $var_name=$var_value)
That's not what you want, what you want is:
$(echo ...) here doesn't make sense.
To output the above, you'd run:
$ echo "$var_name=\$var_value"
So, to interpret it, that's simply:
Note that it can also be used to set individual array elements:
As others have said, if you don't care your code being
bash specific, you can use
However note that it has some side effects.
It limits the scope of the variable to the function where it's run in. So you can't use it for instance in things like:
setvar foo bar
Because that would declare a
foo variable local to
setvar so would be useless.
bash-4.2 added a
-g option for
declare to declare a global variable, but that's not what we want either as our
setvar would set a global var as opposed to that of the caller if the caller was a function, like in:
declare -g "$var_name=$var_value"
setvar myvar 'some value'
echo "1: $myvar"
echo "2: $myvar"
which would output:
2: some value
Also, note that while
declare is called
bash borrowed the concept from the Korn shell's
typeset builtin), if the variable is already set,
declare doesn't declare a new variable and the way the assignment is done depends on the type of the variable.
will produce a different result (and potentially have nasty side effects) if
varname was previously declared as a scalar, array or associative array.