Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK: return value to shell script

Tags:

bash

awk

Is it possible to have an awk command within a bash script return values to a bash variable, i.e.,if my awk script does some arithmetic operations, can I store the answers in variables so, they can be accessed in the bash script. If possible, how to distinguish between multiple return variables. Thanks.

like image 964
Shuvo Shams Avatar asked Mar 14 '12 18:03

Shuvo Shams


People also ask

How do you pass variables from awk to shell?

Passing variables from 'awk' to the shell (its parent process) can be done by 'eval'ing the 'awk' (or an entire pipleline ending with an 'awk' if desired), and having the 'awk' print text which will cause its parent shell to put the information you want into variables.

How do you exit awk command in Unix?

3.3. Like sed's 'q [exit-code]', awk has the exit [expression] command to exit the awk script with a return value, such as 'exit 100'.


2 Answers

No. You can use exit to return an error code, but in general you can't modify the shell environment from a subprocess.

You can also, of course, print the desired content in awk and put it into variables in bash by using read:

read a b c <<< $(echo "foo" | awk '{ print $1; print $1; print $1 }')

Now $a, $b and $c are all 'foo'. Note that you have to use the <<<$() syntax to get read to work. If you use a pipeline of any sort a subprocess is created too and the environment read creates the variables in is lost when the pipeline is done executing.

like image 140
Eduardo Ivanec Avatar answered Sep 17 '22 17:09

Eduardo Ivanec


var=$(awk '{ print $1}')

This should set var to the output of awk. Then you can use string functions or whatever from there to differentiate within the value or have awk print only the part you want.

like image 28
Jake Nicholson Avatar answered Sep 16 '22 17:09

Jake Nicholson