Why is there a syntax error if I don't write 'if' in an END block of AWK?

AWK programs are a series of rules, and possibly functions. Rules are defined as a pattern ((conditions) in your format) followed by an action; either are optional.

BEGIN and END are special patterns.

Thus in

BEGIN {}
(1 == 1) { print "hello"; }
END { if (1 == 1) { print "ended" } }

the patterns are BEGIN, (1 == 1) (and the parentheses aren’t necessary), and END.

Blocks inside braces after a pattern (or without a pattern, to match everything) are actions. You can’t write patterns as such inside a block, each block is governed by the pattern which introduces it. Conditions inside an action must be specified as part of an if statement (or other conditional statement, while etc.).

The actions above are {} (the empty action), { print "hello"; }, and { if (1 == 1) { print "ended" } }.

A block consisting of { (1 == 1) { print "ended" } } results in a syntax error because (1 == 1) is a statement here, and must be separated from the following statement in some way; { 1 == 1; { print "ended" } } would be valid, but wouldn’t have the effect you want — 1 == 1 will be evaluated, then separately, { print "ended" }.


Quoting (english) Wikipedia - Structure of AWK programs

An AWK program is a series of pattern action pairs, written as:

condition { action }
condition { action }
...

where condition is typically an expression and action is a series of commands.

What the article fails to mention is, the condition or pattern is optional. This means in your case (1 == 1) is not needed, because this is always true.


Rewriting the snippet yields

BEGIN {}
{ print "hello"; }
END { print "ended"; }

And having an empty action, you can skip the line altogether

{ print "hello"; }
END { print "ended"; }

Also note that in the example

END {(1 == 1) { print "ended"; }}

The pattern/condition is END and not (1 == 1). 1 == 1 is inside the action, and so is part of the action. This is also the reason, why there's an error.

Tags:

Awk