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?
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?
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
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 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
printf '%s\n' "test1" "test2" "test3"
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)).