downgoon/ioteco

ignore a particular error in bash shell script

Closed this issue · 2 comments

bash 通常执行到某条语句如果出现错误,则会终止后面语句的运行。但是有时候,我们对一些无关紧要的错误,可以跳过,改怎么办?

实验

  • case A
#!/bin/bash
set -e
echo "before error"
cat /no/path/to/file   # statement-1
echo "after error"

输出:

before error
  • case B
#!/bin/bash
set -e
echo "before error"
cat /no/path/to/file  || true  # statement-2
echo "after error"

输出:

before error
after error

结论

在语句后面加|| true,例如: cat /no/path/to/file || true

解释

Every script you write should include set -e at the top. This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

command  
if [ "$?"-ne 0]; then   
    echo "command failed";   
    exit 1;   
fi   

等效:

command || { echo "command failed"; exit 1; }  

What if you have a command that returns non-zero or you are not interested in its return value? You can use command || true, or if you have a longer section of code, you can turn off the error checking, but I recommend you use this sparingly.

set -e # Exit the script if an error happens
set +e # don't bail out of bash script if ccache doesn't exist