Indirection

One particularly useful trick in the bash shell is indirection. You’ll have to be a little bit careful when using it, as it’s easy to get confused as to which variable is which, but it can be a real life-saver.

It is possible to use the value of one variable as the name of anther variable. For example, the following:

for mything in PATH GDMSESSION HOSTNAME
do 
  echo $myvar is ${!myvar}
done

will run like this:

PATH is /usr/bin:/bin:/usr/local/bin:/home/steve/bin:/usr/games
GDMSESSION is gnome
HOSTNAME is declan

Not terribly useful, at first glance. But it means that you can create your own variable names on-the-fly and then access the data within that name:

download.eps
cat empdata.sh
#!/bin/bash
# Employee Data
Dave_Fullname="Dave Smith"
Dave_Country="USA"
Dave_Email=dave@example.com
Jim_Fullname="Jim Jones"
Jim_Country="Germany"
Jim_Email=jim.j@example.com
Bob_Fullname="Bob Anderson"
Bob_Country="Australia"
Bob_Email=banderson@example.com
echo "Select an Employee:"
select Employee in Dave Jim Bob
do
  echo "What do you want to know about ${Employee}?"
  select Data in Fullname Country Email
  do
    echo $Employee               # Jim
    echo $Data                   # Email
    empdata=${Employee}_${Data}  # Jim_Email
    echo "${Employee}'s ${Data} is ${!empdata}"      # jim.j@example.com
    break
  done 
  break
done

empdata.sh

./empdata.sh Select an Employee: ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.