Loading
Home ›
Tech Tip: Dereference Variable Names Inside Bash Functions
Jan 15, 2010 By Mahaveer Darade
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.
______________________
Trending Topics
| OpenLDAP Everywhere Reloaded, Part I | May 23, 2012 |
| Chemistry the Gromacs Way | May 21, 2012 |
| Make TV Awesome with Bluecop | May 16, 2012 |
| Hack and / - Password Cracking with GPUs, Part I: the Setup | May 15, 2012 |
| An Introduction to Application Development with Catalyst and Perl | May 14, 2012 |
| Cryptocurrency: Your Total Cost Is 01001010010 | May 09, 2012 |
- OpenLDAP Everywhere Reloaded, Part I
- Strip DRM from WMV File
- Validate an E-Mail Address with PHP, the Right Way
- Boot with GRUB
- Why Python?
- A Statistical Approach to the Spam Problem
- Chapter 16: Ubuntu and Your iPod
- Why Hulu Plus Sucks, and Why You Should Use It Anyway
- Building an Ultra-Low-Power File Server with the Trim-Slice
- Science the GNU Way, Part I
- Editorial Standards?
4 hours 1 min ago - Great one
5 hours 36 min ago - Common form in many
5 hours 57 min ago - Awsome
11 hours 35 sec ago - Euro 2012 Coupon Codes - Get 20% Off Pavtube TiVo Converter
3 days 9 hours ago - Euro 2012 Big Sale: 20% Off Instant Savings on TiVo Converter
3 days 9 hours ago - MakeMKV works as well, though
3 days 9 hours ago - Euro 2012 Big Sale: 20% Off Instant Savings on TiVo Converter
3 days 10 hours ago - Awesome
4 days 8 hours ago - Who worries approx the
4 days 10 hours ago





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?