bash - 在 bash 脚本中,将所有错误视为成功退出(除了最后一个错误)的最佳方法是什么?

标签 bash macos error-handling

假设你有一个 bash 脚本

#!/bin/bash

echo "hello" > hello
echo "world" > world

diff hello world

如果任何 echo 失败,则退出并返回状态代码 0
diff 应该正常退出,无论它返回什么退出代码

最佳答案

最佳实践是明确地进行错误处理(也就是说,“手动”)。请参阅BashFAQ #105讨论为什么以及如何更自动化的方法容易出错(如果匆忙的话,可以跳过上面的寓言进行下面的练习)。

#!/bin/bash

echo "hello" > hello || exit 0
echo "world" > world || exit 0

# the shell will exit with the status of the last command by default
diff hello world

也就是说,如果您确实想要信任 shell 的内置错误检测,您可以这样做:

#!/bin/bash

# DON'T DO THIS if your logic is at all nontrivial, or if you can't answer all the exercise
# questions at http://mywiki.wooledge.org/BashFAQ/105 correctly.

trap 'exit 0' ERR     # Start handling errors by exiting with status 0
echo "hello" > hello
echo "world" > world
trap - ERR            # Remove the ERR trap, falling back to default behavior

diff hello world

关于bash - 在 bash 脚本中,将所有错误视为成功退出(除了最后一个错误)的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48512204/

相关文章:

bash - 符号链接(symbolic link)循环中的意外 bash 自动完成行为

error-handling - 代号一 - Form.initLaf 抛出随机 "Illegal Access"错误

string - bash:如何在字符串中添加空格?

linux - Bash 脚本(分隔字符串)

java - 无法使用 Jenv 更改 Mac OS 中的 JDK

macos - 我可以在 Electron 中使用 OSX 原生 API

javascript - 评估值Javascript时消除错误

c++ - C++ 中的变量作用域?

c++ - 终端(bash)如何知道引发了什么异常

android - RenderScript 在 macOS Catalina (10.15) 上损坏