Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting an environment variable from awk output within a shell script?

Status
Not open for further replies.

fusi0n

Technical User
Nov 1, 2006
10
US
Hi! I'm reasonably new to awk and shell scripting, and am having difficulties with getting my shell script to set an environment variable based on the awk output from within a shell. I need to be able to reset the variable for each pass of a loop.

Basically, I fetch the name from a file using
awk 'NR==2' R0-results.mol2
And I need to be able to use this output to set the variable mol2file within my shell script run within csh.

I have tried:
awk 'NR==2 {print "set mol2file=" $0}' R0-results.mol2 | sh
and
awk 'NR==2 {print "set mol2file=" $0}' R0-results.mol2

as well as a few other variations that were erased, but all commands will generate the correct command when run at the command line:

set mol2file=pp_5_188_000

which then sets the variable when run as echoed as above. However, I cannot get it to invoke the set variabel command from within the shell script.

I also tried used a system call function:

awk 'NR==2 {system("set filsname=" $0)}' R0-results.mol2

But again, it has the correct command when echoed, but will not be invoked from within the shell script.

What am I doing wrong? How do I invoke a set variable command from within a shell script based on my awk output?

Any help is greatly appreciated!
Thanks!
 
I'm probably misunderstanding this but does your shell support export variable=value?

Alan Bennett said:
I don't mind people who aren't what they seem. I just wish they'd make their mind up.
 
Have you tried:

[tt]eval `awk 'NR==2 {print "set mol2file=" $0}' R0-results.mol2`[/tt]

Or simpler actually:

[tt]set mol2file=`awk 'NR==2' R0-results.mol2`[/tt]

Annihilannic.
 
I hadn't tried the eval version.

Both of them, when run from the command line, will set the variable correctly. However, when I put either one in a shell script and run it, it still doesn't set the variable, claiming it to be undefined when I try to echo it afterwards.
 
You can't set a variable in your current (parent) shell by running another (child) shell script. The only way you can 'run' a script to set variables in the current shell is with the . or source (for C shell) prefix, e.g.

[tt]. /some/scriptname
source /some/scriptname[/tt]

Annihilannic.
 
Well, that would sure explain why I couldn't get anything to work prior! :)

That fixes the biggest problem I was having (which are usually the silliest ones).

Thanks so much!!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top