15

What is wrong with below command

awk 'BEGIN {a = 5;b=6; (a==b)? print "a==b" : print "a!=b"}'

Output :

awk: BEGIN {a = 5;b=6; (a==b)? print "a==b" : print "a!=b"}
awk:                           ^ syntax error

1 Answer 1

34

Like many other programming languages, awk distinguishes between expressions and statements. By and large, statements are actions that are carried out, while expressions are computations that result in a value.

The ternary operator in awk, like its counterpart in C where it comes from, is itself an expression (not a statement) that expects three other expressions as expr1 ? expr2 : expr3. print is a statement. It cannot be used where an expression is called for, hence the syntax error.

Have you tried awk 'BEGIN {a = 5;b=6; print (a==b)? "a==b" : "a!=b"}' ?

Using a statement where an expression is called for cannot make any sense. Statements don't return values. So when you have condition ? stmt1 : stmt2, what is the value computed by the ternary operator? If condition is false, it should be the value of stmt2 but that's not a value, it's an action.

5
  • 1
    There are other languages where statements do return values (ruby comes to mind), but this is a perfect answer for the question. Commented Apr 9, 2016 at 20:15
  • Thanks for that clarification, @glennjackman. I don't know Ruby so maybe I don't know what I'm talking about but my first thought on reading your comment was that guess that means that in Ruby statements kind of are expressions. Commented Apr 10, 2016 at 11:16
  • yes, you can do stuff like this useless example: x = if true; print "yes"; else; print "no"; end Commented Apr 10, 2016 at 11:19
  • I guess this negates the possibility of a construction like (cond1) ? printf("str1") : printf("str2")? Thanks explaining the subtleties of the ternary. EDIT: in fact, using the following ugly construction: str = (cond1) ? sprintf("str1") : sprintf("str2"); printf("%s", str) works, but at this point its almost as compact and much more clear to use if/else :) Commented Sep 24, 2016 at 6:02
  • consider using printf if you don't want to print void lines for unmatched conditions Commented May 15, 2019 at 14:52

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.