bash shell 脚本中的异常处理?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6961389/
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
Exception handling in shell scripting?
提问by Mandar Pande
I'm looking for exception handling mechanism in shell script. Is there any try,catch equivalent mechanism in shell script ?
我正在寻找 shell 脚本中的异常处理机制。shell 脚本中是否有任何 try,catch 等效机制?
回答by mdeous
There is not really a try/catch
in bash (i assume you're using bash), but you can achieve a quite similar behaviour using &&
or ||
.
没有真正的try/catch
in bash(我假设您正在使用 bash),但是您可以使用&&
or实现非常相似的行为||
。
In this example, you want to run fallback_command
if a_command
fails(returns a non-zero value):
在此示例中,您希望fallback_command
在a_command
失败时运行(返回非零值):
a_command || fallback_command
And in this example, you want to execute second_command
if a_command
is successful(returns 0):
在这个例子中,你要执行second_command
ifa_command
成功(返回 0):
a_command && second_command
They can easily be mixed together by using a subshell, for example, the following command will execute a_command
, if it succeeds it will then run other_command
, but if a_command
or other_command
fails, fallback_command
will be executed:
通过使用子shell可以很容易地将它们混合在一起,例如,将执行以下命令a_command
,如果成功则运行other_command
,但如果a_command
或other_command
失败,fallback_command
将执行:
(a_command && other_command) || fallback_command
回答by brightlancer
The if/else structure and exit codes can help you fake some of it. This should work in Bash or Bourne (sh).
if/else 结构和退出代码可以帮助您伪造其中的一些内容。这应该适用于 Bash 或 Bourne (sh)。
if foo ; then
else
e=$? # return code from if
if [ "${e}" -eq "1"]; then
echo "Foo returned exit code 1"
elif [ "${e}" -gt "1"]; then
echo "Foo returned BAD exit code ${e}"
fi
fi
回答by Prasad Kudalkar
{
# command which may fail and give an error
} || {
# command which should be run instead of the above failing command
}
回答by coderofsalvation
Here are two simple bashfunctions which enable eventhandlingin bash:
这里有两个简单的 bashfunctions,它们可以在 bash中启用事件处理:
You could use it for basic exceptionhandling like this:
您可以将它用于基本的异常处理,如下所示:
onFoo(){
echo "onFoo() called width arg !"
}
foo(){
[[ -f /tmp/somefile ]] || throw EXCEPTION_FOO_OCCURED "some arg"
}
addListener EXCEPTION_FOO_OCCURED onFoo
Exceptionhandling using try/catch blocks is not supported in bash, however, you might wanna try looking at the BANGSH framework which supports it (its a bit like jquery for bash).
bash 不支持使用 try/catch 块的异常处理,但是,您可能想尝试查看支持它的 BANGSH 框架(它有点像 bash 的 jquery)。
However, exceptionhandling without cascading try/catch-blocks is similar to eventhandling, which ispossible in almost anylanguage with array-support.
然而,没有级联 try/catch-blocks 的异常处理类似于eventhandling,这在几乎任何具有数组支持的语言中都是可能的。
If you want to keep your code nice and tidy (without if/else verbosity), I would recommend to use events.
如果你想让你的代码保持整洁(没有 if/else 冗长),我建议使用事件。
The suggestion which MatToufoutu recommends (using || and &&) is not recommended for functions, but ok for simple commands. (see BashPitfallsabout the risks)
MatToufoutu 推荐的建议(使用 || 和 &&)不推荐用于函数,但可以用于简单的命令。(请参阅有关风险的BashPitfalls)
回答by Abhishek Jain
Use following to handle error properly where error_exit is function that accepts one argument. In case if argument is not passed then it will throw unknown error with LineNo where actually error is happening. Please experiment before actually uses for production -
使用以下正确处理错误,其中 error_exit 是接受一个参数的函数。如果没有传递参数,那么它会抛出未知错误 LineNo 实际发生错误的地方。请在实际用于生产之前进行试验 -
#!/bin/bash
PROGNAME=$(basename ##代码##)
error_exit()
{
echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
exit 1
}
echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."