Linux 使用二进制返回码动态处理命令的错误报告
在使用其他命令的bash脚本中,我知道我可以使用Linux 使用二进制返回码动态处理命令的错误报告,linux,bash,error-handling,Linux,Bash,Error Handling,在使用其他命令的bash脚本中,我知道我可以使用$?捕获所述命令的返回代码。而此方法通常让我知道命令是成功的0,还是失败的!0,在命令可能只有两个退出代码1和0的情况下,它不提供更多详细信息 例如: 如果在linux中使用reposync命令,我可能会让该命令成功并返回0,但如果由于断开网络而失败,它将返回1,尽管stdout返回更多错误: [<reponame>: <repo_number> of <total_repos> ] Downloading &l
$?
捕获所述命令的返回代码。而此方法通常让我知道命令是成功的0
,还是失败的!0
,在命令可能只有两个退出代码1
和0
的情况下,它不提供更多详细信息
例如:
如果在linux中使用reposync
命令,我可能会让该命令成功并返回0
,但如果由于断开网络而失败,它将返回1
,尽管stdout
返回更多错误:
[<reponame>: <repo_number> of <total_repos> ] Downloading <package>
Could not retrieve package <package> Error was failure: getPackage/<package>: [Errno 256] No more mirrors to try.
不幸的是,这只捕获了消息,不允许我执行报告之外的任何其他错误处理行为。浏览此错误消息真的是处理此情况的最干净的方法吗?假设变量
ERRORS
中有错误文本,您可以使用case
检查某些简单情况,如:
case "$ERRORS" in
*<string>*)
# Code for error that contains <string>
;;
*<string2>*)
# Code for error that contains <string2>
;;
*)
# None matched
;;
esac
您可以将其与案例
语句结合使用
case "$ERRORS" in
*<string>*)
# Code for error that contains <string>
;;
*<string2>*)
# Code for error that contains <string2>
;;
*)
# None matched
;;
esac
echo $ERRORS | perl -n -e'/\[Errno\s*(\d+)\]/ && print $1'