If you prefix the Awk script with BEGIN { exit(0) } END { exit(0) } , you are guaranteed that none of your codes will run. Exiting during BEGIN and END prevents other start and exit blocks from starting. If Awk returns 0, your script was fine; otherwise, a syntax error has occurred.
If you put the code snippet in a separate argument, you will get good line numbers in the error messages. This challenge ...
gawk --source 'BEGIN { exit(0) } END { exit(0) }' --file syntax-test.awk
Gives error messages as follows:
gawk: syntax-test.awk:3: x = f( gawk: syntax-test.awk:3: ^ unexpected newline or end of string
GNU Awk --lint can detect things like global variables and undefined functions:
gawk: syntax-test.awk:5: warning: function `g': parameter `x' shadows global variable gawk: warning: function `f' called but never defined
And the GNU Awk --posix --posix may reveal some compatibility issues:
gawk: syntax-test.awk:2: error: `delete array' is a gawk extension
Update: BEGIN and END
Although the END { exit(0) } block seems redundant, compare the subtle differences between these three calls:
$ echo | awk ' BEGIN { print("at begin") } /.*/ { print("found match") } END { print("at end") }' at begin found match at end $ echo | awk ' BEGIN { exit(0) } BEGIN { print("at begin") } /.*/ { print("found match") } END { print("at end") }' at end $ echo | awk ' BEGIN { exit(0) } END { exit(0) } BEGIN { print("at begin") } /.*/ { print("found match") } END { print("at end") }'
In Awk, exiting BEGIN overrides all other start blocks and prevents any input from being matched. Exiting during END is the only way to prevent all other event blocks from starting; that the third appeal above indicates that no press statements were complied with. The GNU Awk user guide has a section in the exit statement .
source share