“Nesting” Variables in bash

Many thanks to “Gavin Smith” on stackoverflow.com for the first part of this tip.

Expressions like ${${a}} do not work. To work around it, you can use eval:

b=value
a=b
eval aval=\$$a
echo $aval

Output is

value

Thanks for the tip Gavin!

Ok, so why would you want to?

For me, I needed to test that certain variables were being set from an included config file. Using a loop and the nesting technique shown above we can take:

This:

if [ "${KIDFILE}" == "" ] ; then
  echo "ERROR - KIDFILE Not Set"
  exit 1
fi

if [ "${KUSER}" == "" ] ; then
  echo "ERROR - KUSER Not Set"
  exit 1
fi

if [ "${KSERVER}" == "" ] ; then
  echo "ERROR - KSERVER Not Set"
  exit 1
fi

if [ "${KRFILE}" == "" ] ; then
  echo "ERROR - KRFILE Not Set"
  exit 1
fi

if [ "${KLFILE}" == "" ] ; then
  echo "ERROR - KLFILE Not Set"
  exit 1
fi

if [ "${KLINK}" == "" ] ; then
  echo "ERROR - KLINK Not Set"
  exit 1
fi

And replace it with the more elegant:

NEEDVARS="KIDFILE KUSER KSERVER KRFILE KLFILE KLINK"
for MYVAR in ${NEEDVARS}; do
  eval MYVAL=\$${MYVAR}
  if [ "${MYVAL}" = "" ] ; then
    echo "${MYVAR} NOT SET"
    exit 1
  fi
done

Comments are closed, but trackbacks and pingbacks are open.