【问题标题】:How to ignore return value different then 0 when I have set -e?当我设置-e时如何忽略与0不同的返回值?
【发布时间】:2018-11-21 10:28:22
【问题描述】:

我经常在我的 bash 脚本中添加 set -e。但是这次我必须调用一个命令,该命令在成功时返回一些无意义的数字而不是 0。如何告诉 bash 只忽略此命令的返回值。

更改命令或更改其代码以符合标准不是一种选择。

【问题讨论】:

标签: bash


【解决方案1】:

true 始终返回零退出代码。所以你可以这样做

command-with-meaningless-return-value || true

【讨论】:

  • ! command 如果无法理解,则返回 0 表示失败,>= 1 表示例如成功手术的数量(相信我,有如此可怕的偏差)。
【解决方案2】:

如果以后需要用到$?的值,可以这样做:

# A test funtion to demonstrate different exit status values
$ exit_with(){ return $1; }

$ exit_with 0

$ echo $?
0

$ exit_with 4

$ echo $?
4

$ exit_with 4 || true

$ echo $?
0

# capture the exit status rather than clobber it
$ exit_with 4 || exit_status=$?

$ echo $?
0

$ echo $exit_status
4

在这种情况下使用$exit_status 而不是$?。我还没有找到类似?=$?declare ?=$? 的方法

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多