0

I have this situation:

zmx_stderr='\033[1;35m'
zmx_stdout='\033[1;36m'


tag='foobar'

tailing(){
  echo "tailing logs for ${tag} ...";
  while read line; do
   echo -e "$zmx_${1} $tag $1${zmx_no_color}: $line"
  done;
}

someone calls tailing() with:

tailing stderr
tailing stdout

how can I look up the zmx_stdout and zmx_stderr dynamically?

This doesn't work:

$zmx_${1}

I just get this:

stdout foobar stdout:

but I am looking for:

foobar stdout:

with control chars being generated.


2 Answers2

1

You could use a helper variable to build the name of the target variable and then use variable indirection:

zmx_var=zmx_$1
echo -e "${!zmx_var} $tag $1${zmx_no_color}: $line"
Freddy
  • 25,565
1

With bash version 4.4 (I think) and above, you can use a "nameref"

$ foo_bar=hello
$ set -- bar
$ declare -n "var=foo_$1"
$ echo "$var"
hello
glenn jackman
  • 85,964