Search code examples
linuxbashindirection

Linux Bash how to grab output and put it back in the script using for loop


Variable's value in bash can be easily called with echo $var command like this

user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ echo $a $b $c
1 2 a+b
user@linux:~$ 

What I'm trying to accomplish is to replace x with the actual value in a,b,c

user@linux:~$ a=1; b=2; c=a+b
user@linux:~$ for i in a b c; do echo "$i = x"; done
a = x
b = x
c = x
user@linux:~$ 

By using similar for loop, I hope I can get an output like this

a = 1
b = 2
c = a+b

Solution

  • Use indirection:

    $ for i in a b c; do echo "$i = ${!i}"; done
    a = 1
    b = 2
    c = a+b
    

    Documentation

    Indirection is explained in man bash:

    If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.