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
Best Answer
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, butawk
interprets this as FALSE. You need to invert the logics.