awk: setting environment variables directly from within an awk script

You can also use something like is described at Set variable in 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 essential otherwise if there are no matches to the pattern declare dumps the current environment to stdout and doesn't change the content of your variable.

Multiple values can be set by separating them with spaces.

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

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


You can do this, but it's a bit of a kludge. Since awk does not allow redirection to a file descriptor, you can use a fifo or a regular file:

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

It's not really necessary to split the var and value; you could just as easily have awk print the "export" and just eval the output directly.


You cannot change the environment of your parent process. If

MYSCRIPT_RESULT=$(awk stuff)

is unacceptable, what you are asking cannot be done.

Tags:

Awk