gawk versus mawk: BEGIN block handling of empty piped input
0 reputation · 13 Jun 2022, 04:18 UTC
0 reputation · 13 Jun 2022, 04:18 UTC
This inquiry examines how two major awk implementations gawk and mawk treat the execution sequence of BEGIN and END blocks when input is empty or when no records match the pattern-action rule. The objective is to document whether the pattern-action block is uniformly suppressed across both runtimes or if divergent handling introduces portability risk for scripts that depend on deterministic initialization or summary output.
Research confirms that awk invokes BEGIN before the first record and END after the last yet the behavior when no records exist varies between implementations. The FS and RS variable scoping as well as the presence of piped input from /dev/null or empty streams can influence which code paths are taken. No cross-implementation specification mandates identical skipping of the pattern-action block leaving script authors to contend with undocumented differences.
34775 reputation · 13 Jun 2022, 06:06 UTC
Both gawk and mawk execute the BEGIN block before any input is read and the END block after all input has been processed, even when the input stream is empty. Consequently, no pattern‑action (rule) block is run for lack of records.
echo -n | … or piping /dev/null) there are zero records, so the pattern‑action block is never entered.echo -n | gawk 'BEGIN{print "BEGIN"} {print $0} END{print "END"}'Expected output:
BEGIN
ENDecho -n | mawk 'BEGIN{print "BEGIN"} {print $0} END{print "END"}'Expected output is identical.
echo -n | gawk 'BEGIN{FS=":"} {print $1} END{print "done"}'Only done appears after END; no middle line.
Older mawk releases (pre‑1.3.4) were reported to skip the END block on empty input. If you must support legacy systems, check your mawk version:
mawk -W version 2>/dev/null || mawk --versionIf the version is older than 1.3.4, consider upgrading or adding an explicit END guard.
If you are targeting a system with mawk < 1.3.4, please confirm the exact mawk version in use, as this changes the recommendation (you may need to rely on an explicit END block or upgrade).
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.