本文翻译自:Bash ignoring error for a particular command
I am using following options 我正在使用以下选项
set -o pipefail
set -e
In bash script to stop execution on error. 在bash脚本中停止执行错误。 I have ~100 lines of script executing and I don't want to check return code of every line in the script. 我有大约100行脚本正在执行,并且我不想检查脚本中每一行的返回码。
But for one particular command, I want to ignore the error. 但是对于一个特定的命令,我想忽略该错误。 How can I do that? 我怎样才能做到这一点?
#1楼
参考:https://stackoom.com/question/l7wH/重击忽略特定命令的错误
#2楼
The solution: 解决方案:
particular_script || true
Example: 例:
$ cat /tmp/1.sh
particular_script()
{
false
}
set -e
echo one
particular_script || true
echo two
particular_script
echo three
$ bash /tmp/1.sh
one
two
three
will be never printed. three
将永远不会打印。
Also, I want to add that when pipefail
is on, it is enough for shell to think that the entire pipe has non-zero exit code when one of commands in the pipe has non-zero exit code (with pipefail
off it must the last one). 此外,我想补充一点,当pipefail
启用时,当管道中的命令之一具有非零退出代码时,shell认为整个管道具有非零退出代码就足够了(关闭pipefail
必须将最后一个一)。
$ set -o pipefail
$ false | true ; echo $?
1
$ set +o pipefail
$ false | true ; echo $?
0
#3楼
Just add || true
只需添加|| true
|| true
after the command where you want to ignore the error. 要忽略错误的命令后为|| true
。
#4楼
More concisely: 更简洁地说:
! particular_script
From the POSIX specification regarding set -e
(emphasis mine): 从关于set -e
的POSIX规范 (强调我的):
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 ! 启用此选项时,如果简单命令由于“ Shell错误的后果”中列出的任何原因而失败,或者返回退出状态值> 0,并且在一段时间,直到或if关键字之后,则不属于复合列表的一部分,并且不是AND或OR列表的一部分,也不是前面带有!的管道。 reserved word , then the shell shall immediately exit. 保留字 ,然后外壳应立即退出。
#5楼
Instead of "returning true", you can also use the "noop" or null utility (as referred in the POSIX specs ) :
and just "do nothing". 除了“ returning true”之外,您还可以使用“ noop”或null实用程序(如POSIX规范中所述 ) :
并且仅“不执行任何操作”。 You'll save a few letters. 您将保存一些字母。 :) :)
#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."
#6楼
Don't stop and also save exit status 不要停止并保存退出状态
Just in case if you want your script not to stop if a particular command fails and you also want to save error code of failed command: 万一您希望脚本在特定命令失败时不停止,并且还希望保存失败命令的错误代码,以防万一:
set -e
EXIT_CODE=0
command || EXIT_CODE=$?
echo $EXIT_CODE