How to print the variable name along with its value?
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
)
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'
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 )
%