This is a followup to my earlier question.
I am validating the number of fields in /etc/passwd using this handy snippit. In the following example, the users 'fieldcount1' and 'fieldcount2' have the wrong number of fields:
$ awk -F: ' NF!=7 {print}' /etc/passwd
fieldcount1:x:1000:100:fieldcount1:/home/fieldcount1:/bin/bash::::
fieldcount2:blah::blah:1002:100:fieldcount2:/home/fieldcount2:/bin/bash:
$ echo $?
0
As you'll notice, awk will exit with an return status of 0. From it's standpoint, there are no problems here.
I would like to incorporate this awk statement into a shell script. I would like to print all lines which are error, and set the return code to be 1 (error).
I can try to force a particular exit status, but then awk only prints a single line:
$ awk -F: ' NF!=7 {print ; exit 1}' /etc/passwd
fieldcount1:x:1000:100:fieldcount1:/home/fieldcount1:/bin/bash::::
$ echo $?
1
Can I force awk to exit with a return status of '1', and print all lines which match?
; echo $?
after this awk statement. However,echo $?
is never run because theEND {exit err}'
terminates the script. Is there a way to set the return status without exiting? – Stefan Lasiewski Jul 13 '11 at 17:38exit err
terminates awk, it doesn't terminate the script. Do you haveset -e
in that script, by any chance? If so, you've told the shell to exit if a command returns a nonzero status; if you want to test the status, useif awk …; then echo ok; else echo fail; fi
. – Gilles 'SO- stop being evil' Jul 13 '11 at 22:50set -e
set. That explains the strange behavior that I'm seeing. Thanks for pointing that out. – Stefan Lasiewski Jul 13 '11 at 23:21&&
operator, it's worth keeping in mind that "0 is true but false is 1 in the shell". – Skippy le Grand Gourou Oct 31 '19 at 13:37