Variable indirection in shell scripts

Recently, I had to find a way to do variable indirection in a shell script. More specifically, I wanted to write a function that takes two arguments and interprets one of them as a string, and the other one as a variable to which that string should be added – a simple append function.

Usually, that would be a good occasion to switch to some more comfortable scripting language than the unix shell, but sometimes that's not possible. So here is how to do it (thanks to an article on TLDP):

append() {
    # Appends the value of $1 to the variable indicated by $2
    eval $2=\"\$$2 $1\"

eval is a very useful shell built-in that converts a string to a command, performing the regular shell variable substitution. In the small function above, this means that when calling the function like this:

A_VARIABLE="initial value"
append "some string" "A_VARIABLE"

The line

eval $2=\"\$$2 $1\"

first becomes (by regular shell variable substitution)

eval A_VARIABLE="$A_VARIABLE some string"

which is then evaluated as a command, again with variable substitution:

A_VARIABLE="initial value some string"

At least, I hope that this is what is actually going on... Quote escaping in shell scripts can be tricky sometimes. Many more useful examples of indirect references can be found in the referenced article.

Comments !