Quote:
|
Originally Posted by sharathkv25
Hi,
I am able to access the shell variable in awk, as you can see in my my script posted above.
|
Not really. When you do this:
Code:
$ VAR=test
$ awk '{ print '$VAR' }'
...you are executing the command:
Code:
awk '{ print test }'
Awk never sees the string "$VAR" - the shell pre-expands this before invoking awk - you have basically excluded it from the single quotes and allowed the shell to interpolate $VAR. That it is working is an illusion, which will break in many cases - e.g. your variable has a space or tab in it. For example:
Code:
$ VAR="my test"
$ awk '{ print '$VAR' }'
awk: cmd. line:1: { print my
awk: cmd. line:1: ^ unexpected newline or end of string
Quote:
I need to know how to set a value to a shell variable from AWK, so I can use the variable in shell later on?
Thanks
|
You can't set something in the environment of a parent process. The environment variables are inherited by a child process from it's parent. If you write to the environment variables in a process, it will modify the copy in the memory space of that process, but cannot send it to the parent.
You can however take the standard output of a program, and assign that to a variable in the shell. This is a very different mechanism, but depending on what you want to do, it can have a similar effect:
Code:
$ var=$(echo "J. R. Bob Dobbs" |awk '{ print $3 }')
This will execute the command:
Code:
$ echo "J. R. Bob Dobbs" |awk '{ print $3 }'
...and assign the output of that command to the variable var. In this case, var will be "Bob".
A more general description is that $(command) is interpolated as the output of "command".