Awk: setting environment variables directly from awk script

first post here, but was a lurker for ages. I searched for a long time, but I can’t find what I want (many obscure topics that do not ask what this topic offers ...). not new to awk or scripts, just a little rusty :)

I am trying to write an awk script that will set the values ​​of the env shell at runtime - for another bash script to pick up and use later. I can't just use stdout from awk to report this value that I want to set (i.e., "export whatever = awk cmd here"), since it is already directed to the "result file" that awkscript creates (plus I have a few variables export in the final code).

As an example of a test script, to dismantle my problem:

echo $MYSCRIPT_RESULT          # returns nothing, not currently set
echo | awk -f scriptfile.awk   # do whatever, setting MYSCRIPT_RESULT as we go
echo $MYSCRIPT_RESULT          # desired: returns the env value set in scriptfile.awk 

inside scriptfile.awk, I tried (without success)

1 /) creating and executing an adhoc line directly:

{
  cmdline="export MYSCRIPT_RESULT=1"
  cmdline
}

2 /) using the system function:

{
  cmdline="export MYSCRIPT_RESULT=1"
  system(cmdline)
}

... but they do not work. I suspect that these two commands create a subshell in the awk shell that executes and does what I ask (verified by touching files as a test), but as soon as the cmd / system calls are complete, the subshell dies, unfortunately taking it, what I installed with it is therefore my env configuration changes do not stick to the awk caller viewpoint.

: env awk , env awk? ?

adhoc/system, , , ( "" -, script, imo ), , !

// !

+5
3

.

MYSCRIPT_RESULT=$(awk stuff)

, , , .

+5

, . awk , fifo :

$ mkfifo fifo
$ echo MYSCRIPT_RESULT=1 | awk '{ print > "fifo" }' &
$ IFS== read var value < fifo
$ eval export $var=$value

var value; "" .

+2

You can also use something like described in Set a variable in the current shell from awk

 unset var
 var=99
 declare $( echo "foobar" | awk '/foo/ {tmp="17"} END {print "var="tmp}' )
 echo "var=$var"
var=

The awk END clause is important if there is no match for the declare pattern, unloads the current environment into stdout, and does not change the contents of your variable.

Several values ​​can be specified by dividing them into spaces.

 declare a=1 b=2
 echo -e "a=$a\nb=$b"

NOTE: declare is only bash, for other shells use eval with the same syntax.

+1
source

All Articles