In a
Linux Journal Tech tip is shown how you can dereference a variable, when it is passed as string to a function. It uses the bash ! operator.
Code:
DerefernceVariablePassedToFunction() {
if [ -n "$1" ] ; then
echo "value of [${1}] is: [${!1}]"
else
echo "Null parameter passed to this function"
fi
}
Variable="LinuxJournal"
DerefernceVariablePassedToFunction Variable
This will now print LinuxJournal.
I just wondered why he did not use
eval like this
Code:
#/bin/sh
dereference() {
if [ -n "$1" ] ; then
eval echo value of \$1 is: \$$1
else
echo "Null parameter passed to this function"
fi
}
variable="Just use 'eval'"
dereference variable
This has the same effect. A run with
sh -vx so you can see the double interpretation pass performed by
eval
Code:
sh -vx dereference.sh
#/bin/sh
dereference() {
if [ -n "$1" ] ; then
eval echo value of \$1 is: \$$1
else
echo "Null parameter passed to this function"
fi
}
variable="Just use 'eval'"
+ variable=Just use 'eval'
dereference variable
+ dereference variable
echo value of $1 is: $variable
value of variable is: Just use 'eval'
The first pass converts
echo value of \$1 is: \$$1
into
echo value of $1 is: $variable
\$1 is seen by the shell as a "$" followed by a '1' . The "\" prevents
the shell from interpreting $1 as the first parameter, as it normally would do.
\$$1is parsed as a literal "$" followed by the function parameter $1 which contains the string "variable"
The second and last pass re-processes this
echo value of $1 is: $variable
and without any "\" to prevent variable expansion, produces the wanted result:
value of variable is: Just use 'eval'