ruby system command check exit code

user1530318 picture user1530318 · Sep 10, 2013 · Viewed 88.9k times · Source

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

or

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

Answer

Stefan picture Stefan · Sep 10, 2013

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

Furthermore

An error status is available in $?.

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

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