2

This is my AWK script

#!/bin/awk -f
(1 == 2)
{
  print "OK"
}

And the output is

OK
OK
OK
...

The condition 1==2 is clearly wrong, but the action is executed nonetheless. Why is that?!

ToniAz
  • 430
  • 1
  • 6
  • 24

1 Answers1

2

Command terminating semi colon is optional in awk if next command starts on a new line.

Here (1 == 2) is interpreted separately from {...} block that starts from new line. (1 == 2) is returning false and nothing is printed but next { ... } block is considered independent and here OK is printed for each row.

You should fix it by using:

#!/bin/awk -f
(1 == 2) {
  print "OK"
}

Now anything inside { ... } will be evaluated only when condition succeeds.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Now why doesn't any AWK tutorial mention any of this?! Thank you! – ToniAz Apr 22 '20 at 22:08
  • 1
    @ToniAz per the book Effective Awk Programming, 4th Edition, by Arnold Robbins (THE Awk reference): `Each rule’s action has to begin on the same line as the pattern.`. See about 2/3 of the way down in the section on [Statements vs Lines](https://www.gnu.org/software/gawk/manual/gawk.html#Statements_002fLines). Don't use shebangs to invoke the awk interpreter though, use the shebang to invoke your shell and then call awk inside the shell script just like you'd call any other tool, see https://stackoverflow.com/a/61002754/1745001. – Ed Morton Apr 22 '20 at 22:18
  • @EdMorton I want to take your advice, I really do. But my issue is that using a ton of single quotes really obfuscates my script. Unless I plan to use AWK in a way similar to the example you linked, I don't see a problem with the AWK shebang. – ToniAz Apr 22 '20 at 22:37
  • 3
    If you are using a ton of single quotes then you're doing something wrong. There should be 2 single quotes - 1 single quote at the start of your awk script and one at the end of your awk script, that's all. You can of course use shebangs if you like and make your own decision when you get more experience, at least now you're aware of the issue so you'll recognize it when you hit it (and it's a common problem so you'll probably hit it soon). – Ed Morton Apr 22 '20 at 22:42