Personal Programming Notes

To err is human; to debug, divine.

Bash Programming Cookbook

The blog lists some frequently used code snippets found in shell programming.

Indirect expansion

Using indirect expansion expression ${!var}, you can use the value of one variable to tell you the name of another vairable.

Indirect expansion
1
2
3
4
5
6
7
$ export xyzzy=plugh ; export plugh=cave

$ echo ${xyzzy}  # normal, xyzzy to plugh
plugh

$ echo ${!xyzzy} # indirection, xyzzy to plugh to cave
cave

According to bash man page, the exceptions to this are the expansions of ${!prefix*} and ${!name[@]}. ${!prefix*} expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When ${!prefix@} is used and the expansion appears within double quotes, each variable name expands to a separate word. On the other hand, ${!name[*]}, if name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When ${!name[@]} is used and the expansion appears within double quotes, each key expands to a separate word.

Exceptions to Indirect Expansion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
:~> export myVar="hi"
:~> echo ${!my*}
    myVar

:~> cat temp.sh
#!/bin/bash

letters=(a b c d)
echo ${!letters[*]}
echo ${!letters[@]}

:~> bash temp.sh
0 1 2 3
0 1 2 3

Reference:

General reference