Feng Tian
Feng Tian

Reputation: 1589

How to display variable name itself rather than the value in shell

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

Answers (2)

chepner
chepner

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

Feng Tian
Feng Tian

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

Related Questions