Register
It is currently Mon Oct 20, 2014 3:13 pm

Bash variable indirection IN a variable?!


All times are UTC - 6 hours


Post new topic Reply to topic  [ 4 posts ] 
Author Message
 PostPosted: Sun Apr 03, 2011 6:14 am   

Joined: Sun Apr 03, 2011 5:58 am
Posts: 7
Hello,

Need some help here!

Code:
#!/bin/bash

FILE="/etc/passwd"

var=guys
hello_guys=root

cat $FILE | eval grep -i \$hello_$var # Works

var2=`cat $FILE | eval grep -i \$hello_$var` # Dont work
echo $var2 # Dont Work



I Think you see what i wanna do, but why doesent it work within a variable?

Thanks in advance!


Top
 Profile  
 PostPosted: Sun Apr 03, 2011 7:08 am   
User avatar

Joined: Sun Jun 27, 2010 12:57 am
Posts: 192
It's not the variable that is causing the problem, but the backticks. The backticks cause an extra evaluation round, which in turn 'destroys' your escaped \$. So you can either escape the escaped $ or you can forget about backticks altogether and use $().
Code:
eval grep -i "\$hello_$var" "$FILE"
echo `eval grep -i "\\\$hello_$var" "$FILE"`
echo $(eval grep -i "\$hello_$var" "$FILE")


Top
 Profile  
 PostPosted: Sun Apr 03, 2011 9:55 am   

Joined: Sun Apr 03, 2011 5:58 am
Posts: 7
Thanks Patsie!

You are a doll! :)

Can you explain why i need the eval command, i've googled it but i doesent realy understand?

//Barty


Top
 Profile  
 PostPosted: Sun Apr 03, 2011 11:21 am   
User avatar

Joined: Sun Jun 27, 2010 12:57 am
Posts: 192
Normally your shell goes through an evaluation step to substitute variables ($var) with their actual contents.
The eval command forces an extra evaluation step. Take the 3 echo's below:
Code:
echo "$hello_$var"
echo "\$hello_$var"
eval echo "\$hello_$var"

The first echo will be evaluated as if $hello_ and $var are 2 separate variables, because they both start with a $-sign. so the echo will evaluate to nothing, because $hello_ isn't defined anywhere, and to 'guys', because that's what $var is filled with.
If you escape the $-sign before 'hello', the evaluation will just print the $-sign. Therefor 'hello' is no variable anymore and thus the string hello_ is printed. $var isn't excaped, so the eval step will substitute it with it's contents guys. This results in the string $hello_guys.
But you want the contents of $hello_guys so you have to force another eval step.

ps: I didn't know you are into guys, 'doll'. Unfortunately, I'm not.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 4 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP