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

后端 未结 7 1723
我在风中等你
我在风中等你 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 14:52

    Instead of if construct, you can leverage the short-circuit evaluation:

    #!/usr/bin/env bash
    
    echo $[1+1]
    echo $[2/0]              # division by 0 but execution of script proceeds
    echo $[3+1]
    (echo $[4/0]) || exit $? # script halted with code 1 returned from `echo`
    echo $[5+1]
    

    Note the pair of parentheses which is necessary because of priority of alternation operator. $? is a special variable set to exit code of most recently called command.

提交回复
热议问题