5

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
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 at 3:02
5

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 '20 at 15:30
  • smart man ^^ ;) Nov 19 '20 at 22:41

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.