For example:
a=s1;b=s2; for i in $a $b ; do echo $i ; done
I want to get a and b
NOT s1 and s2
How could I do it?
If you are using bash
or ksh
, indirect parameter expansion is safer than using eval
.
a=s1
b=s2
for i in a b; do
echo "$i=${!i}"
done
If you are using zsh
, the syntax is slightly different.
for i in a b; do
echo "$i=${(P)i}"
done
Other shells might have different syntax; check its documentation for details.
If you are using a shell (e.g. /bin/sh
or dash
) without indirect parameter expansion, you'll have to use eval
:
for i in a b; do
eval "echo $i=\$$i"
done
Here, eval
is safe because you had explicit control over the value of i
. In general, any parameters expanded in the argument to eval
should be validated to ensure you don't execute code you didn't expect to.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments