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

后端 未结 7 1737
我在风中等你
我在风中等你 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:59

    I often include a function called run() to handle errors. Every call I want to make is passed to this function so the entire script exits when a failure is hit. The advantage of this over the set -e solution is that the script doesn't exit silently when a line fails, and can tell you what the problem is. In the following example, the 3rd line is not executed because the script exits at the call to false.

    function run() {
      cmd_output=$(eval $1)
      return_value=$?
      if [ $return_value != 0 ]; then
        echo "Command $1 failed"
        exit -1
      else
        echo "output: $cmd_output"
        echo "Command succeeded."
      fi
      return $return_value
    }
    run "date"
    run "false"
    run "date"
    

提交回复
热议问题