Reputation: 1589
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?
Upvotes: 0
Views: 49
Reputation: 531768
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.
Upvotes: 2
Reputation: 1589
I got it!
a=s1;b=s2; for i in \$a \$b ; do echo $i ; done
This will get a
and b
If you also want to use the value, try this:
a=s1;b=s2; for i in \$a \$b ; do eval "echo $i" ; done
This will get s1
and s2
Upvotes: 0