Tech Tip: Dereference Variable Names Inside Bash Functions

 in

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.
______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

re: what are you using it for?

geofs's picture
# i've got a list of directories, like this:

dir_app1="/opt/config/app1"
dir_app2="/opt/config/app2"
dir_app3="/opt/config/test/app_3"

# i then create the directory structure
# the trick here is ${!dir_*} that expands to the name
# of all variables beginning with dir_

for i in ${!dir_*}; do
    echo "  making directory ${!i}"
    mkdir -p ${!i}
done

# then i change access rights
chmod 755 $dir_app1
chmod 700 $dir_app2
...

It has been described already for ages, especially in ABS guide.

przemoc's picture

It's a falsehood stating ABS guide teaches that variable names passed as parameters to functions cannot be dereferenced. Below you can find more and less portable examples in ABS guide.

http://tldp.org/LDP/abs/html/abs-guide.html#INDREF
http://tldp.org/LDP/abs/html/abs-guide.html#INDFUNC
http://tldp.org/LDP/abs/html/abs-guide.html#DEREFERENCECL
http://tldp.org/LDP/abs/html/abs-guide.html#REFPARAMS
http://tldp.org/LDP/abs/html/abs-guide.html#EMBARR

Good practice needs verifying whatever you want to write and publicize. Remember about that next time!

Nice but won't work if text is the same as a variable name

PerfMonk's picture

In your example, if you call :
DerefernceVariablePassedToFunction "Variable"

It will return "value of [Variable] is: [LinuxJournal]" ...

Unexpected since we gave it the text "Variable" not the variable...

Sorry I have not enough knowledge in bash scripting to suggest a better solution.

Regards,

BT

Strings are strings

fest3er8's picture

Ah, but "Variable" is the same as Variable, as far as the shell is concerned; all parameters are strings. You don't pass a variable name (symbol) to a function; you pass a string.

So

DerefernceVariablePassedToFunction "Variable"

is the same as

DerefernceVariablePassedToFunction Variable

or...

lingrlongr's picture

something like this could be used for other shells, like KSH, and may be more portable...

#!/usr/bin/ksh

deref()
{
    if [ -n "$1" ]; then
        localvar=$(eval echo \$$1)
        echo "value of [${1}] is: [${localvar}]"
    else
        echo "Null parameter passed to this function"
    fi
}


var="some text to display"

deref var
deref

this will display:

value of [var] is: [some text to display]
Null parameter passed to this function

great info

k.sangeeth's picture

..I already started using it :)

Sangeeth Keeriyadath
www.sangeek.com

thx

lingrlongr's picture

i've used this on numerous occasions where my code will dynamically construct a "structured" variable name then retrieve the value for that variable, if it is set.

for instance, if i have a list of database tables that need to be reorganized and i want to reorganize against a particular index, i'll set up a config file:

#!/bin/bash

# these values may be in another file and sourced in
reorg_my_table_1_index="id"
reorg_my_table_2_index="location"

deref()
{
    if [ -n "$1" ]; then
        localvar=$(eval echo \$$1)
        echo "value of [${1}] is: [${localvar}]"
    else
        echo "Null parameter passed to this function"
    fi
}

for tab in my_table_1 my_table_2 my_table_3; do
    echo $(deref "reorg_${tab}_index")
done

what are you using it for?

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix