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.
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.
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'.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With