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

后端 未结 11 2087
渐次进展
渐次进展 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:43

    You actually don't need to use exit at all. Logically, no matter what the result of grep, your script is going to exit anyway. Since the exit value of a shell script is the exit code of the last command that was run, just have grep run as the last command, using the -v option to invert the match to correct the exit value. Thus, your script can reduce to just:

    grep -vqP "STATUS: (?!Perfect)" recess.txt
    

    EDIT:

    Sorry, the above does not work when there are other types of lines in the file. In the interest of avoiding running multiple commands though, awk can accomplish the entire shebang with something like:

    awk '/STATUS: / && ! /Perfect/{exit 1}' recess.txt
    

    If you decide you want the output that grep would have provided, you can do:

    awk '/^STATUS: / && ! /Perfect/{print;ec=1} END{exit ec}' recess.txt
    

提交回复
热议问题