Dereferencing BASH Variables

This is a handy way of iterating over variable names and their values in BASH.

#!/bin/bash
# define some test variables, all prefixed with test_
test_one=value_one
test_two=value_two
test_three=value_three
test_four=value_four
test_five=value_five

for var in ${[email protected]}
# expand the names of all variables prefixed with test_
# and assign them to ${var} in this loop
do
# echo ${var} and dereference ${var} to display its value
  echo The value of ${var} = ${!var}
done

The output of the above example is as follows:

./test.sh
test_five = value_five
test_four = value_four
test_one = value_one
test_three = value_three
test_two = value_two
This is useful in scripts in which variables are added/removed often, and tasks need applying to each variables. To have all of the actions in the for loop apply to a new variable, all you need to do is add the new variable and prefix it with test_ and the match will take care of it for you.

Dereferencing variables is also useful in functions, where the function needs both the name of the variable and its value:

function test_dereference {
> echo -e "I was passed the name of a variable, ${1}.
> Its dereference value is ${!1}" ;
> }
$ function test_dereference {
> echo -e "I was passed the name of a variable, ${1}.
> Its dereferenced value is ${!1}" ;
> }
$ somevariable=somevalue
$ test_dereference somevariable
I was passed the name of a variable, somevariable.
Its dereferenced value is somevalue
$