8

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
3
  • like so awk 'condition{exit 1}'?
    – Sundeep
    Sep 9, 2016 at 9:55
  • 1
    @spasic: You can't do like that. In this case the condition is the 4th column did not match the regular expression, so it can exit immediately at the start if the 1st line does not match the condition.
    – cuonglm
    Sep 9, 2016 at 10:04

2 Answers 2

18

for me, this is awk's unforgiveable sin; if in need of an error status, I pipe to grep dot, as opposed to the awk gymnastics above

$ date | awk '/Fri/'
Fri May 29 21:26:18 EDT 2020
$ date | awk '/Fri/' | grep .
Fri May 29 21:27:11 EDT 2020
$ echo $?
0
$ date | awk '/Mon/' | grep .
$ echo $?
1
2
  • I like this more than the original solution.
    – iTayb
    Nov 18, 2020 at 15:30
  • smart man ^^ ;) Nov 19, 2020 at 22:41
6

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 }'
1
  • Or you can set the variable beforehand: 'BEGIN { rc=1 } $1=="foo" { print $0; rc=0; exit } END { exit rc }' Feb 10, 2021 at 3:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .