As we all know, when you execute the "exit" command in AWK, it doesn't
really exit your program. Instead, it transfers control to your END
block(s) and those get executed. Essentially, "exit" means "act as if
you've read all the lines of all the input files". This is sort of a
mis-feature, but of course, it is the way AWK is and certainly can't be
changed.
However, sometimes, you really need to exit NOW - and skip any END block
processing. Usually, this is when some error condition is detected, that
requires an immediate abort after printing an error message. As it turns
out, TAWK has this covered, as they have an "abort()" function that does
exactly this. AFAIK (& CMIIW), there is no equivalent functionality in
GAWK. Needless to say, I think there should be. Consider this post to be
a feature request. Thank you.
Note, BTW, that this problem is particularly acute if one is writing
library code, since the library code doesn't know if the user has a END
clause or not. See the example below for how this is handled by the
GAWK-supplied library function "assert".
Currently available workarounds (in GAWK) include:
1) Set a flag and check that in a specially supplied END block (that
you assume/hope will be called before any user-written END block)
Here is "assert.awk" from the GAWK distribution:
--- Code ---
# assert --- assert that a condition is true. Otherwise exit.
#
# Arnold Robbins,
arn...@skeeve.com, Public Domain
# May, 1993
function assert(condition, string)
{
if (! condition) {
printf("%s:%d: assertion failed: %s\n",
FILENAME, FNR, string) > "/dev/stderr"
_assert_exit = 1
exit 1
}
}
END {
if (_assert_exit)
exit 1
}
--- Code ---
2) Call a function you know doesn't exist. This is a hack that I've
been using in GAWK for decades now. It works and it makes it very
clear that something has gone horribly wrong. Conveniently, you
can use abort(), which exists in TAWK, but not in any other AWK (to
my knowledge). It gets the job done in any event. Observe:
% gawk4 'BEGIN { abort() }';echo $status
gawk4: cmd. line:1: fatal: function `abort' not defined
2
%
3) Use the "call_any" library to call the system "exit" function. This
also gets the job done. Observe:
% gawk4 'BEGIN { print "Start";exit 1;print "Done"}END {print "in END block"}' ; echo $status
Start
in END block
1
% gawk4 -l call_any 'BEGIN { print "Start";call_any("ii","exit",1);print "Done"}END {print "in END block"}' ; echo $status
Start
1
--
There are two kinds of Republicans: Billionaires and suckers.
Republicans: Please check your bank account and decide which one is you.