DaemonForums  

Go Back   DaemonForums > Miscellaneous > Programming

Programming C, bash, Python, Perl, PHP, Java, you name it.

 
 
Thread Tools Display Modes
Prev Previous Post   Next Post Next
  #1   (View Single Post)  
Old 27th January 2010
J65nko J65nko is offline
Administrator
 
Join Date: May 2008
Location: Budel - the Netherlands
Posts: 3,154
Thanked 182 Times in 149 Posts
Default Dereferencing sh variables

In a Linux Journal Tech tip is shown how you can dereference a variable, when it is passed as string to a function. It uses the bash ! operator.

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

Variable="LinuxJournal"
DerefernceVariablePassedToFunction Variable
This will now print LinuxJournal.

I just wondered why he did not use eval like this
Code:
#/bin/sh

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

variable="Just use 'eval'"
dereference variable
This has the same effect. A run with sh -vx so you can see the double interpretation pass performed by eval
Code:
 sh -vx dereference.sh 
#/bin/sh

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

variable="Just use 'eval'"
+ variable=Just use 'eval'
dereference variable 
+ dereference variable
echo value of $1 is: $variable
value of variable is: Just use 'eval'
The first pass converts
echo value of \$1 is: \$$1
into
echo value of $1 is: $variable
\$1 is seen by the shell as a "$" followed by a '1' . The "\" prevents
the shell from interpreting $1 as the first parameter, as it normally would do.

\$$1is parsed as a literal "$" followed by the function parameter $1 which contains the string "variable"


The second and last pass re-processes this
echo value of $1 is: $variable
and without any "\" to prevent variable expansion, produces the wanted result:
value of variable is: Just use 'eval'
__________________
You don't need to be a genius to debug a pf.conf firewall ruleset, you just need the guts to run tcpdump
Reply With Quote
 

Tags
bash ! operator, curly braces, dereference, eval, variable name

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
passing make args/variables to builds of prerequisite ports jbhappy FreeBSD Ports and Packages 2 18th July 2008 02:35 PM


All times are GMT. The time now is 12:25 PM.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
Content copyright © 2007-2010, the authors
Daemon image copyright ©1988, Marshall Kirk McKusick