|
Programming C, bash, Python, Perl, PHP, Java, you name it. |
|
Thread Tools | Display Modes |
|
|||
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 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 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' echo value of \$1 is: \$$1into 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: $variableand 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 |
Tags |
bash ! operator, curly braces, dereference, eval, variable name |
|
|
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 |