Bash – Double variable substitution in bash

bashvariable substitution

Program snippet:

BASH_MIN_REQ="2.05"
BINUTILS_MIN_REQ="2.12"
BISON_MIN_REQ="1.875"

BASH_CURR=$(bash --version | head -n1 | cut -d"(" -f1 | cut -d" " -f4)
BINUTILS_CURR=$(ld --version | head -n1 | cut -d" " -f7)
BISON_CURR=$(bison --version | head -n1 | cut -d" " -f4)

list=(BASH BINUTILS BISON)

for progs in ${list[@]}; do
    echo "$progs: ${${progs}_MIN_REQ}:${${progs}_CURR}"
done

Expected Output:

BASH: 2.05:4.3.11
BINUTILS: 2.12:2.24
BISON: 1.875:3.0.2

Notice the variables initialized with the values. I want to substitute ${progs}_MIN_REQ with $BASH_MIN_REQ and then again with the value it was initialized with that is 2.05. And do this inside the for loop so that will be easier for me to write the code as I'll have to write only 1 echo statement instead of 3.

Actual output:

bad substitution

I know what I have written in echo is wrong. But is there a way to double substitute the variables. Otherwise I'll have to write lots of echo statements.

Best Answer

You can do this with indirection

for progs in ${list[@]}; do
     a="${progs}_MIN_REQ"
     b="${progs}_CURR"
     echo "$progs: ${!a}:${!b}"
done
Related Question