Bash: One-liner to exit with the opposite status of a grep command?

后端 未结 11 2080
渐次进展
渐次进展 2021-02-06 22:08

How can I reduce the following bash script?

grep -P \"STATUS: (?!Perfect)\" recess.txt && exit 1
exit 0

It seems like I should be able

11条回答
  •  别那么骄傲
    2021-02-06 22:32

    I came across this, needing an onlyif statement for Puppet. As such, Tgr's bash solution wouldn't work, and I didn't want to expand the complexity as in Christopher Neylan's answer.

    I ended up using a version inspired by Henri Schomäcker's answer, but notably simplified:

    grep -P "STATUS: (?!Perfect)" recess.txt; test $? -eq 1
    

    Which very simply inverts the exit code, returning success only if the text is not found:

    • If grep returns 0 (match found), test 0 -eq 1 will return 1.
    • If grep returns 1 (no match found), test 1 -eq 1 will return 0.
    • If grep returns 2 (error), test 2 -eq 1 will return 1.

    Which is exactly what I wanted: return 0 if no match is found, and 1 otherwise.

提交回复
热议问题