重击忽略特定命令的错误

本文翻译自: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 -ePOSIX规范 (强调我的):

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值