Bash:出错时退出和清理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36335186/
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:26:22  来源:igfitidea点击:

Bash: Exit and cleanup on error

basherror-handling

提问by Nico Schl?mer

In my Bash scripts, I would like to make sure that the script exits as soon as there is an error. (E.g., to avoid a mistaken rm -f *after a failed cd some_directory.) For this reason, I always use the -eflag for bash.

在我的 Bash 脚本中,我想确保脚本在出现错误时立即退出。(例如,为了避免rm -f *失败后的错误cd some_directory。)出于这个原因,我总是使用-ebash 标志。

Now, I would alsolike to execute some cleanup code in some of my scripts. From this blog postI gathered

现在,我喜欢以执行一些我的脚本的一些清理代码。从这篇博文中我收集到

#!/bin/bash

cd invalid_directory
echo ':('

function clean_up {
  echo "> clean_up"
  exit 0
}
trap clean_up EXIT

The output I get is

我得到的输出是

./test.sh: line 3: cd: invalid_directory: No such file or directory
:(
> clean_up

so it does what's advertised. However, when using -efor bash, I'm only getting

所以它做广告。但是,当-e用于 bash 时,我只得到

./test.sh: line 3: cd: invalid_directory: No such file or directory

so the script exits without calling clean_up.

所以脚本退出而不调用clean_up.

How can I have a bash script exit at all errors andcall a clean up script every time?

我怎么可以在所有的错误bash脚本退出调用清理脚本,每一次?

回答by chepner

You are never reaching the trapcommand; your shell exits before the trap is configured.

你永远达不到trap命令;您的外壳在配置陷阱之前退出。

set -e
clean_up () {
    ARG=$?
    echo "> clean_up"
    exit $ARG
} 
trap clean_up EXIT
cd invalid_directory
echo "Shouldn't reach this"

However, it's better to do your own error handling. You often want to vary your behavior depending on the exact reason whyyour script is exiting, something that is more complicated to do if you are running a single handler for allexits (even if you restrict your trap to ERRinstead of EXIT).

但是,最好自己进行错误处理。你经常要取决于具体的理由来改变自己的行为,为什么你的脚本退出,一些更复杂的做,如果你正在运行一个单一的处理程序全部退出(即使你限制你的陷阱ERR,而不是EXIT)。

cd invalid_directory || { echo "cd to invalid_directory failed" >&2; exit 1; }
echo "Shouldn't reach this"

This doesn't mean you have to abandon your clean_upfunction. It will still be executed for explicit exits, but it should be restricted to code that should run no matter whyyour script exits. You can also put a trap on ERRto execute code that should only be executed if you script is exiting with a non-zero exit status.

这并不意味着您必须放弃您的clean_up功能。它仍然会在显式退出时执行,但它应该仅限于无论您的脚本为何退出都应该运行的代码。您还可以设置陷阱ERR以执行仅在脚本以非零退出状态退出时才应执行的代码。