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.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.
Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.
Sponsored by ActiveState
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
| Introduction to MapReduce with Hadoop on Linux | Jun 05, 2013 |
- Containers—Not Virtual Machines—Are the Future Cloud
- Non-Linux FOSS: libnotify, OS X Style
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Linux Systems Administrator
- Validate an E-Mail Address with PHP, the Right Way
- Introduction to MapReduce with Hadoop on Linux
- RSS Feeds
- Weechat, Irssi's Little Brother
- New Products
- Tech Tip: Really Simple HTTP Server with Python
- Poul-Henning Kamp: welcome to
1 hour 48 min ago - This has already been done
1 hour 49 min ago - Reply to comment | Linux Journal
2 hours 34 min ago - Welcome to 1998
3 hours 23 min ago - notifier shortcomings
3 hours 46 min ago - heroku?
5 hours 23 min ago - Android User
5 hours 25 min ago - Reply to comment | Linux Journal
7 hours 18 min ago - compiling
10 hours 7 min ago - This is a good post. This
15 hours 20 min ago
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
re: what are you using it for?
# 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.
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
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
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 Variableor...
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 derefthis will display:
great info
..I already started using it :)
Sangeeth Keeriyadath
www.sangeek.com
thx
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") donewhat are you using it for?