Awk exit code if regular expression did not match

awkgawkregular expression

I want to get exit code 1 if the 4th column did not match the regular expression, but it seems that awk will return 0, even though the regular expression did not match.

Any idea how to make awk return 1 if the regexp did not match?

root@server:~# netstat -nap|grep "LISTEN\b"
tcp        0      0 0.0.0.0:873                 0.0.0.0:*                   LISTEN      1144/rsync          
tcp        0      0 1.2.3.4.5:53                0.0.0.0:*                   LISTEN      25213/named         
tcp        0      0 127.0.0.1:53                0.0.0.0:*                   LISTEN      25213/named         
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      28888/sshd          
tcp        0      0 0.0.0.0:9686                0.0.0.0:*                   LISTEN      1150/stunnel        
tcp        0      0 127.0.0.1:953               0.0.0.0:*                   LISTEN      25213/named         
root@server:~# netstat -nap|grep "LISTEN\b"|awk '$4 ~ /:80$/ {print $NF}'
root@server:~# echo $?
0

Best Answer

You can set a variable to hold the return code, then negate the variable before quitting:

netstat -nap    |
grep "LISTEN\b" |
awk '$4 ~ /:80$/ {rc = 1; print $NF}; END { exit !rc }'

If you don't need \b, then you can remove grep part:

netstat -nap | awk '/LISTEN/ && $4 ~ /:80$/ {rc = 1; print $NF}; END { exit !rc }'
Related Question