Ruby系统调用获取有关命令失败的信息

HRÓ*_*LFR 3 ruby unix shell

假设我有一个简单的命令行解释器,如下所示:

while true
  print '> '
  cmd = gets.chomp
  break if cmd =~ /^(exit|quit)/
  system(cmd) || puts('Command not found or invalid.')
end
Run Code Online (Sandbox Code Playgroud)

我想,而不是"命令未找到或无效".消息得到一个实际的错误消息,就像你从bash得到的消息.我该怎么做?

Vla*_*ich 6

好吧,如果它是类似unix的系统,你实际上可以将2>&1附加到你的命令:

system(cmd + ' 2>&1 ')
Run Code Online (Sandbox Code Playgroud)

这会将你的stderr重定向到stdout

另一种方法是使用%x [...]:

irb(main):027:0> def hello
irb(main):029:2*   %x[hello]
irb(main):030:2> rescue Exception => e
irb(main):031:2>   puts e.message
irb(main):033:1> end
=> nil
irb(main):034:0> hello
No such file or directory - hello
=> nil
irb(main):035:0>
Run Code Online (Sandbox Code Playgroud)

意思是,您可以挽救命令执行并返回异常消息