假设你有一个 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/