【问题标题】:Rescuing bash/system STDERR in Ruby在 Ruby 中拯救 bash/system STDERR
【发布时间】:2013-06-12 20:09:29
【问题描述】:

我正在使用我的 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"

它肯定会抛出正确的错误,但来自 system(...) 的 shell 错误并没有被挽救。有什么想法吗?

【问题讨论】:

标签: ruby shell exception system


【解决方案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

【讨论】:

    【解决方案2】:

    来自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"
    

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

    【讨论】:

    • 一个澄清:终端输出显示“line 1: eho: command not found”,但从 $?.to_s 检索到的错误显示“pid 32303 exit 127”。如何访问实际的终端输出而不是状态码?
    • @user2490003 你不能;它不是那样工作的。如果您需要命令的输出,请使用反引号 (`sh my_shell_script.sh`)。这会让你重新使用begin/rescue
    猜你喜欢
    • 2013-06-28
    • 2012-07-31
    • 2010-10-07
    • 2011-01-12
    • 2010-12-15
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    相关资源
    最近更新 更多