In a bash script, I have a code returned from the output of another program in ipsumCode, and customised explanatory notes corresponding to each code (there are hundreds) set as a string to make for easy editing.

Instead of relying on if statements for each code and building a custom note for each there, I'm trying to reduce it all down to one if test that can display the appropriate output.



msg_456="Some description here."
msg_599="A different description here."
msg_600="Yet another different description here."

# $ipsumCode is set by output from another program, but hard-code it here to test


if [ "$ipsumCode" -ge 456 ]; then
    printf "$identifier: $ipsumMessage\n"

Since ipsumCode is 599 in this instance, how do I display the contents of msg_599?

Above displays:

FooBar: msg_599

Desired output:

FooBar: A different description here.

I've looked at several similar questions and answers, but all deal with combining outputs in various ways, rather than building a string name from another string and outputting the contents of the matching string.

1 Answers

Nick On Best Solutions

You need to use indirect expansion:

printf "$identifier: ${!ipsumMessage}\n"

Using your whole example this gives:

FooBar: A different description here.