In a Bash script, how can I exit the entire script if a certain condition occurs?

后端 未结 7 1680
我在风中等你
我在风中等你 2020-11-29 14:30

I\'m writing a script in Bash to test some code. However, it seems silly to run the tests if compiling the code fails in the first place, in which case I\'ll just abort the

相关标签:
7条回答
  • 2020-11-29 15:11

    A SysOps guy once taught me the Three-Fingered Claw technique:

    yell() { echo "$0: $*" >&2; }
    die() { yell "$*"; exit 111; }
    try() { "$@" || die "cannot $*"; }
    

    These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try() your statement and code on.

    Explanation

    (based on flying sheep comment).

    • yell: print the script name and all arguments to stderr:
      • $0 is the path to the script ;
      • $* are all arguments.
      • >&2 means > redirect stdout to & pipe 2. pipe 1 would be stdout itself.
    • die does the same as yell, but exits with a non-0 exit status, which means “fail”.
    • try uses the || (boolean OR), which only evaluates the right side if the left one failed.
      • $@ is all arguments again, but different.
    0 讨论(0)
提交回复
热议问题