user1530318 user1530318 - 5 months ago 41
Ruby Question

ruby system command check exit code

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")

I want something like

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.

Is that possible at all?

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'


From the documentation:

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


An error status is available in $?.

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

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