ruby系统命令检查退出代码 [英] ruby system command check exit code

查看:439
本文介绍了ruby系统命令检查退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆ruby中的系统调用,如下所示,我想同时检查他们的退出代码,以便我的脚本退出,如果该命令失败。

I have a bunch of system calls in ruby such as the following and I want to check their exit codes simultaneously so that my script exits out if that command fails.

system("VBoxManage createvm --name test1")
system("ruby test.rb")

我想要类似

系统(VBoxManage createvm --name test1,0 )< - 其中第二个参数检查退出代码并确认系统调用成功,如果不成功,则会引发错误或执行某种操作。

system("VBoxManage createvm --name test1", 0) <-- where the second parameter checks the exit code and confirms that that system call was successful, and if not, it'll raise an error or do something of that sort.

这是可能的吗?

我尝试过这样的东西,也没有工作。

I've tried something along the lines of this and that didn't work either.

system("ruby test.rb")
system("echo $?")

`ruby test.rb`
exit_code = `echo $?`
if exit_code != 0
  raise 'Exit code is not zero'
end


推荐答案

文档


系统返回 true 如果命令给出零退出状态, false
非零退出状态。

system returns true if the command gives zero exit status, false for non zero exit status. Returns nil if command execution fails.



system("unknown command")     #=> nil
system("echo foo")            #=> true
system("echo foo | grep bar") #=> false

此外


$?中有错误状态。



system("VBoxManage createvm --invalid-option")

$?             #=> #<Process::Status: pid 9926 exit 2>
$?.exitstatus  #=> 2

这篇关于ruby系统命令检查退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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