bash 如何从失败的命令返回退出代码 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36130299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:23:12  来源:igfitidea点击:

How to return exit code 0 from a failed command

linuxbashshellunix

提问by meso_2600

I would like to return exit code "0" from a failed command. Is there any easier way of doing this, rather than:

我想从失败的命令中返回退出代码“0”。有没有更简单的方法来做到这一点,而不是:

function a() {
  ls aaaaa 2>&1;
}

if ! $(a); then
  return 0
else
  return 5
fi

回答by Michael Daffin

Simply append return 0to the function to force a function to always exit successful.

只需附加return 0到函数即可强制函数始终成功退出。

function a() {
  ls aaaaa 2>&1
  return 0
}

a
echo $? # prints 0

If you wish to do it inline for any reason you can append || trueto the command:

如果您出于任何原因希望内联执行,您可以附加|| true到命令:

ls aaaaa 2>&1 || true
echo $? # prints 0

If you wish to invert the exit status simple prepend the command with !

如果您希望简单地反转退出状态,请在命令前加上 !

! ls aaaaa 2>&1
echo $? # prints 0

! ls /etc/resolv.conf 2>&1
echo $? # prints 1

Also if you state what you are trying to achieve overall we might be able to guide you to better answers.

此外,如果您说明您总体上想要达到的目标,我们或许可以指导您找到更好的答案。