当我设置-e时,如何忽略返回值不同于0?

Dim*_*hev 8 bash

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

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

nan*_*dhp 11

true始终返回零退出代码.所以你可以做到

command-with-meaningless-return-value || true
Run Code Online (Sandbox Code Playgroud)

  • 或者`!命令`如果不可理解,它返回0表示失败,> = 1表示例如成功操作的数量(相信我,有这种可怕的像差). (3认同)

Bru*_*sky 5

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

# 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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,使用$exit_status代替$?. 我还没有找到做类似?=$?declare ?=$?