2

I have this:

test1="1"
test2="2"
test3="3"

for i in "$test1" "$test2" "$test3"; do
        echo "$i"
done ;

I want to echo the $i variable name, not its content.

The echo output should be "test1", or "test2", or "test3"

How can I do this?

  • 3
    What is the actual problem you are trying to solve? – Alexander Jun 19 '17 at 12:42
2

The meaning of for i in "$test1" "$test2" "$test3" is: $i will hold the content of the three variables test1, test2, test3 - which will actually holds: 1, 2, 3

If you want to print test1, test2 and test3 you should call them without the $ sign, i.e. the actual name, not their value

The following code (without the $ before the test1/2/3 variables will print what you want:

test1="1"
test2="2"
test3="3"

for i in "test1" "test2" "test3"; do
        echo "$i"
done ;

execution result:

test1
test2
test3
  • Alternatively, without an explicit loop: printf '%s\n' "test1" "test2" "test3" – Kusalananda Jun 19 '17 at 12:21
  • 4
    But this isn't echoing the name of a variable, it is just printing a collection of strings. – terdon Jun 19 '17 at 12:27
  • @terdon And that is exactly what a variable name is: a string of characters (usually: a-zA-Z_). – Arrow Jun 19 '17 at 18:38
  • 1
    @Arrow yes, of course. However, if all you want to do is print an arbitrary string, why in the world would you go to the trouble of setting it as a variable first? I had assumed (and I admit I may have been wrong since the OP accepted this) that the OP needed to print the name of a variable else they would have just echoed their string directly. – terdon Jun 19 '17 at 22:51
15

If you really want to do this, just do that:

#!/bin/bash
test1='1'
test2='2'
test3='3'
for v in "test1" "test2" "test3"; do
        echo "The variable's name is $v"
        echo "The variable's content is ${!v}"
done 

But you probably would prefer to use arrays rather than dynamic variable names as this can be seen as a bad practice and make your code harder to understand. So consider this, much better, form:

#!/bin/bash
test[0]='1'
test[1]='2'
test[2]='3'
for ((i=0;i<=2;i++)); do
        echo "The variable's name is \$test[$i]"
        echo "The variable's content is ${test[$i]}"

done 
3

Use single quotes:

for i in '$test1' '$test2' '$test3'; do
    echo "$i"
done

or else, escape the dollar signs with a backslash:

for i in \$test1 \$test2 \$test3; do
    echo "$i"
done
  • The best answer until now +1 – Luciano Andress Martini Jun 19 '17 at 15:11
  • @LucianoAndressMartini "Don't overthink it!" – Kaz Jun 19 '17 at 15:44
2

ksh93 or Bash:

$ test1=aa; test2=bb; test3=cc
$ for x in "${!test@}" ; do echo "$x" ; done 
test1
test2
test3

(note that the variables are expanded in lexical order (so test10 would come before test2)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.