Bash:错误的优雅功能死亡 [英] Bash: graceful function death on error

查看:128
本文介绍了Bash:错误的优雅功能死亡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来模拟函数中 set -e 的行为,但只能在该函数的范围内。



基本上,我想要一个函数,如果任何简单的命令触发 set -e ,它会返回1上一级。我们的目标是将高风险工作集合分解为函数,以便我能够优雅地处理它们。 解决方案

如果您想要任何失败的命令要返回1,可以通过使用 ||来执行每条命令来实现返回1



例如:

  false ||返回1#这将永远返回1 

我非常喜欢从不让任何命令失败处理。对于我的脚本,我使用异常处理技术,以不返回代码的方式返回错误,并捕获所有错误(使用bash陷阱)。任何带有非零返回码的命令都会自动意味着未正确处理的情况或错误,并且一旦出现这种情况,我宁愿我的脚本失败。


I'm trying to find a way to emulate the behavior of set -e in a function, but only within the scope of that function.

Basically, I want a function where if any simple command would trigger set -e it returns 1 up one level. The goal is to isolate sets of risky jobs into functions so that I can gracefully handle them.

解决方案

If you want any failing command to return 1, you can achieve that by following each command with || return 1.

For instance:

false || return 1  # This will always return 1

I am a big fan of never letting any command fail without explicit handling. For my scripts, I am using an exception handling technique where I return errors in a way that is not return codes, and trap all errors (with bash traps). Any command with a non-zero return code automatically means an improperly handled situation or bug, and I prefer my scripts to fail as soon as such a situation occurs.

这篇关于Bash:错误的优雅功能死亡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆