5

I'm trying to perform a grep inside awk using system() which according to the manual should return the exit code of the command being run.

$ cat foo.txt
bar
$ grep -q bar foo.txt; echo $?
0
$ awk 'BEGIN{ if ( system( "grep -q bar foo.txt" ) ) { print "yes" } else { print "no" } }'
no

If I remove the -q I can see that grep is indeed finding bar so it should exit 0 and therefore print yes, no?

$ awk 'BEGIN{ if ( system( "grep bar foo.txt" ) ) { print "yes" } else { print "no" } }'
bar
no

Completely removing grep from the equation:

$ awk 'BEGIN{ if ( system( "true" ) ) { print "yes" } else { print "no" } }'
no
  • 3
    if (0) { ... } else { ... } – Kusalananda Jan 16 at 21:02
  • @Kusalananda: Well that is just awkward. – jesse_b Jan 16 at 21:08
  • 1
    Perhaps if (system("true") == 0) { ...success... } is less awkward – ottomeister Jan 16 at 21:28
  • 2
    I don't get why you would call grep from awk. However I can see it could be useful to call other programs (e.g. json or xml prasers). – ctrl-alt-delor Jan 16 at 21:45
  • 2
    @Jesse_b don't call grep from awk like that, think about the stack of calls shell { awk { system { shell { grep } } } } and the fact you're spawning a new shell for every call to grep. What you describe is a common use case and there's better ways to do it - post a new question if you'd like help with that. – Ed Morton Jan 17 at 2:54
12

In shell, the exit code 0 stands for success of a command, and any other for failure (and its reason). That's what system returns: 0 for success, but awk interprets this as FALSE. You need to invert the logics.

  • 3
    Well doh, thanks! – jesse_b Jan 16 at 21:04
  • 1
    Right, it's the difference between an exit status (0=success, non-zero=failure) and a condition (0=false, non-zero=true). What 0 means depends if your using it as an exit status as in a shell test if [ 0 ]; then or a condition as in an awk if statement if ( 0 ) { – Ed Morton Jan 17 at 2:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.