在shell命令失败时引发异常?

编程入门 行业动态 更新时间:2024-10-09 11:23:23
本文介绍了在shell命令失败时引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在用Ruby编写一些脚本,并且需要通过shell命令与一些非Ruby代码进行交互。我知道至少有 6种不同的执行方式不幸的是,来自Ruby的这些命令似乎都不会在shell命令失败时停止执行。

I'm writing some scripts in Ruby, and I need to interface with some non-Ruby code via shell commands. I know there are at least 6 different ways of executing shell commands from Ruby, unfortunately, none of these seem to stop execution when a shell command fails.

基本上,我在寻找一种等效于以下功能的东西:

Basically, I'm looking for something that does the equivalent of:

set -o errexit

...在Bash脚本中。理想情况下,该解决方案将在命令失败时(即通过检查非零返回值)引发异常,例如将stderr作为消息。编写起来并不难,但似乎应该已经存在。

...in a Bash script. Ideally, the solution would raise an exception when the command fails (i.e., by checking for a non-zero return value), maybe with stderr as a message. This wouldn't be too hard to write, but it seems like this should exist already. Is there an option that I'm just not finding?

推荐答案

最简单的方法是创建一个新函数(或重新定义一个现有的)调用system()并检查错误代码。

Easiest way would be to create a new function (or redefine an existing one) to call system() and check the error code.

类似的东西:

old_sys = system def system(...) old_system(...) if $? != 0 then raise :some_exception end

这应该做您想要的。

更多推荐

在shell命令失败时引发异常?

本文发布于:2023-11-25 06:29:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628675.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   命令   shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!