4

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.

2 Answers 2

5

You can do this with indirection

for progs in ${list[@]}; do
     a="${progs}_MIN_REQ"
     b="${progs}_CURR"
     echo "$progs: ${!a}:${!b}"
done
1
for progs in "${list[@]}"; do
  eval 'echo "$progs: ${'"${progs}"'_MIN_REQ}:${'"${progs}"'_CURR}"'
done
3
  • Your implementation has syntax errors at ${' Commented May 27, 2016 at 16:40
  • @AbhimanyuSaharan, how so? "${_list[@]}" is ksh/zsh/bash/yash specific, but the eval line should be valid syntax in any Bourne-like shell. Commented May 27, 2016 at 17:59
  • "$progs: ${' has errors. Anyways meuh's answer worked for me. Commented May 27, 2016 at 18:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .