Tech Tip: Dereference Variable Names Inside Bash Functions

We often read (including in the book Advanced Bash-Scripting Guide by Mendel Cooper) that if we pass variable names as parameters to functions, they will be treated as string literals and cannot be dereferenced (ie the value is not available). But this is not so, variable names can be passed as parameters to functions and they can be dereferenced to obtain the value of the variable with the given name.

The following script demonstrates this:

DerefernceVariablePassedToFunction() {
    if [ -n "$1" ] ; then
        echo "value of [${1}] is: [${!1}]"
    else
        echo "Null parameter passed to this function"
    fi
}


Variable="LinuxJournal"
DerefernceVariablePassedToFunction Variable

If we put above code in a file and run it, we will get output as:

$ /bin/bash DereferenceVarInFunction.sh
value of [Variable] is: [LinuxJournal]

The secret here is the "!" used in the variable expansion "${!1}". The bash manual states:

If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.
Load Disqus comments