I have a script whose main purpose is to gather some information and output it in a table. The primary part is an awk script:
awk '
{
# do some stuff, including calculating dwt
printf(format, a, b, c, d)
}
END {
# pass on dwt
}
' inputfile
The main purpose of the awk is to create and show the table. But there is a side value dwt
that it also calculates that I need elsewhere in the main script, and I am trying to figure out the best way to pass it out without disrupting the table output.
There are two ways I know I can do this:
- Save the value to a temporary file:
END { print dwt > "tempfile" }
then read it outsideread dwt <tempfile; rm -f tempfile
. But even with more care taken to avoid clobbering existing files than shown here, I prefer to avoid this - if nothing else, I'd rather not leave temp files lying around just because a job got interrupted at the wrong time. - Send the value to stdout as well, but flagged. Pipe stdout into a following routine that catches and directs the flagged output appropriately, but sends the rest on:
awk '
...
END {
print "dwt:" dwt
}
' inputfile | while read line; do
if [[ $line = dwt:* ]]; then
dwt="${line#dwt:}"
else
echo "$line"
fi
done
But that seems contrived and inelegant.
I am wondering if anyone knows a better method. I've experimented with using a different file descriptor, but so far have not managed to get that to work. I have not figured out how to get the information out of the file descriptor and into the dwt environment variable without disrupting stdout as well.
print ... | "cat >&2"
), but I'm not yet sure how you'd integrate that into the overall script. – Jeff Schaller Oct 24 '19 at 16:31dwt
value (assuming it's an env variable). – Jeff Schaller Oct 24 '19 at 16:36END {exit dwt}
). This will only "work" if dwt is an integer with a value from 0 to 255. It also abuses the concept of exit codes, and will cause the script to terminate if run withset -e
and the ec is not immediately captured (e.g. withif
or||
or&&
). – cas Oct 25 '19 at 03:30mktemp
or similar available (to avoid the kind of race conditions made possible by tempfiles), i'd strongly recommend using that and passing the tempfile name to awk, rather than hard-coding it. – cas Oct 25 '19 at 03:40