set -e and short tests

前端 未结 4 792
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 10:17

When I was new to shell scripting, I used a lot of short tests instead of if statements, like false && true.

Then later I learned u

4条回答
  •  渐次进展
    2020-12-23 11:10

    The Single UNIX Specification describes the effect of set -e as:

    When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.

    As you see, a failing command in an AND list will not make the shell exit.

    Using set -e

    Starting shell scripts with set -e is considered a best practice, since it is usually safer to abort the script if some error occurs. If a command may fail harmlessly, I usually append || true to it.

    Here is a simple example:

    #!/bin/sh
    set -e
    
    # [...]
    # remove old backup files; do not fail if none exist
    rm *~ *.bak || true
    

提交回复
热议问题