有人可以在 bash 中解释这个 try/catch 替代方案吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14964529/
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
Could someone explain this try/catch alternative in bash?
提问by Harrys Kavan
So I found out that bash does not handle exceptions (there is no try/catch). For my script, I would like to know if a command was successful or not.
所以我发现 bash 不处理异常(没有 try/catch)。对于我的脚本,我想知道命令是否成功。
This is the part of my code right now:
这是我现在代码的一部分:
command = "scp -p$port $user:$password@$host:$from $to"
$command 2>/dev/null
if (( $? == 0 )); then
echo 'command was successful'
else
echo 'damn, there was an error'
fi
The things I don't understand are:
我不明白的事情是:
- line 3, why do I have to put the
2behind the$command? - line 5, what exactly is it with this
$?
- 第 3 行,为什么我必须把 放在
2后面$command? - 第 5 行,这到底是
$怎么回事?
回答by legrandviking
$?means the return code of the last executed command.
$?表示上次执行命令的返回码。
2>means redirecting the stderr(standard error stream) output to /dev/null.
2>意味着将stderr(标准错误流)输出重定向到/dev/null.
回答by William
Just FYI, this will also work:
仅供参考,这也将起作用:
if some_command 2>/dev/null ; then
echo 'command was successful'
else
echo 'damn, there was an error'
fi

