7

Is there any way I can print the variable name along with its value?

j=jjj
k=kkk
l=lll

for i in j k l
do
    ....
done

Expected output (each variable on a separate line):

j = jjj 
k = kkk
l = lll

Can any one suggest a way to get the above result?

17

In simple way:

j="jjj"
k="kkk"
l="lll"

for i in {j,k,l}; do echo "$i = ${!i}"; done

The output:

j = jjj
k = kkk
l = lll

  • ${!i} - bash variable expansion/indirection (gets the value of the variable name held by $i)
  • 1
    You can make {j,k,l} short with {j..l} also : ) – αғsнιη Oct 12 '17 at 3:25
  • @αғsнιη, it's reasonable for extended ranges, as long as there only 3 items - {j,k,l} would be enough – RomanPerekhrest Oct 12 '17 at 8:30
  • 1
    j k l would be enough. – Stéphane Chazelas Oct 12 '17 at 11:43
6

If you have bash v4.4 or later you can use ${VAR@A} Parameter expansion operator.

This is discussed in the Bash manual under section 3.5.3 Shell Parameter Expansion

'A' Operator

The expansion is a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with its attributes and value.

So with this you can do:

j="jjj"
k="kkk"
l="lll"

for i in {$j,$k,$l}; do 
    echo "${i@A}"
done

And your result should be:

j='jjj'
k='kkk'
l='lll'
5

Or in zsh use declare -p

% j=jjj; k=kkk; l=(l l l)               
% for v in j k l; do declare -p $v; done
typeset j=jjj
typeset k=kkk
typeset -a l=( l l l )
% 
  • 3
    works with Bash too – Steven Penny Oct 11 '17 at 23:48
2

Whilst ${!i} is a cleaner and faster solution, for completeness, the indirect reference can also be obtained with the following example:

 foo=bar
 bar=baz
 $ echo $foo
 bar
 $ eval echo \$${foo}
 baz

Therefore:

 j="jjj"
 k="kkk"
 l="lll"

 for i in {j,k,l}; do
   echo "$i = `eval echo \\$${i}`"
 done

Gives:

 j = jjj
 k = kkk
 l = lll

References:

Indirect References

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.