在Ruby中拯救bash / system STDERR

时间:2013-06-16 21:29:52

标签: ruby shell exception system

我正在使用我的Ruby脚本来调用系统命令,如下所示

puts "Reached point #1"

begin
  system("sh my_shell_script.sh")
rescue StandardError => e
  puts "There was an error"
end

puts "Reached point #2"

我故意在我的shell脚本中添加了一个错误,因此它会失败(即我拼写为“echo”为“eho”)。我希望我的Ruby脚本输出它到达标记#1,然后解救错误以显示“出现错误”。

相反,我得到了:

"Reached point #1"
line 1: eho: command not found
"Reached point #2"

它肯定会抛出正确的错误,但系统(...)的shell错误不会被挽救。有什么想法吗?

2 个答案:

答案 0 :(得分:5)

来自documentation for Kernel#system

  如果命令为退出状态为零,则

system返回true,非零退出状态为false。如果命令执行失败,则返回nil$?中提供了错误状态。

这意味着您有很多方法可以继续(其中没有一种方法可以解决引发的错误),具体取决于您想要的确切故障信息。如果您只是希望区分成功执行命令以及所有形式的失败的零退出状态,这是您的代码的翻译:

puts "Reached point #1"

unless system("sh my_shell_script.sh")
  puts "There was an error"
end

puts "Reached point #2"

您当然可以通过查看返回值来区分命令执行失败和非零退出状态,如果需要,您可以根据文档从$?获取退出状态代码。

答案 1 :(得分:1)

  

相反,我得到了:

"Reached point #1"
line 1: eho: command not found
"Reached point #2"

换句话说,它获得了救援,但并不像你期望的那样。

你真正想要的可能更像是这样:

ret = system("sh my_shell_script.sh")
puts $? unless ret

http://www.ruby-doc.org/core-2.0/Kernel.html#method-i-system