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

标签 ruby unix shell

假设我有一个像这样的简单命令行解释器:

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

我想,而不是“未找到或无效的命令”。 message 得到一个实际的错误信息,就像你从 bash 得到的一样。我该怎么做?

最佳答案

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

system(cmd + ' 2>&1 ')

这会将您的 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>

也就是说,你可以挽救命令执行并返回异常信息

关于Ruby 系统调用获取有关命令失败的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6945585/

相关文章:

Ruby 将方法定义中的参数括起来

java - Ruby 路径和带有存档的小程序

unix - 如何在 unix 中使用 UUENCODE 发送 Zip 文件

linux - 为什么我不能从另一个终端写入我的终端设备的标准输入

bash - 用于确定文件大小的 Linux 脚本

linux - 在 shell 脚本中从应用程序的输出中检索单词

ruby - 如何确定 XFS 文件系统是否以编程方式卡住?

linux - 这两个命令有什么区别

linux - 如果不是当前文件,则重命名文件

ruby - 在 Ruby 中实现 DSL 以生成特定于域的 XML