Wednesday, June 26, 2013

Programatically named variables in bash.

Suppose you wanted to do the following in bash:

for label in a b c d e f
do
  variable_${label}=${label}
done

This has the intended result of setting a series of variables:
variable_a
variable_b
variable_c
variable_d
variable_e
variable_f

But if what if you want to dereference them programatically?
for label in a b c d e f
do
  echo ${variable_${label}}
done
is not acceptable bash syntax.
But there is a way...
We can abuse export and env. We set them with:
for label in a b c d e f
do
  export variable_${label}=${label}
done
We can then programmatically dereference the variables by searching for them in the output of env and using awk to get their value.
for label in a b c d e f
do
  echo "`env | grep variable_${label} | awk -F= '{print $2}'`"
done
How's that for bash abuse?