在shell命令失败时引发异常? [英] Raise exception on shell command failure?

查看:121
本文介绍了在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命令失败时引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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