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
From the documentation:
Furthermore
system
returnsfalse
if the command has an non-zero exit code, ornil
if there is no command.Therefore
or
should work, and are reasonably concise.
You're not capturing the result of your
system
call, which is where the result code is returned:Remember each
system
call or equivalent, which includes the backtick-method, spawns a new shell, so it's not possible to capture the result of a previous shell's environment. In this caseexit_code
istrue
if everything worked out,nil
otherwise.The
popen3
command provides more low-level detail.For me, I preferred use `` to call the shell commands and check $? to get process status. The $? is a process status object, you can get the command's process information from this object, including: status code, execution status, pid, etc.
Some useful methods of the $? object:
One way to do this is to chain them using
and
or&&
:The second call won't be run if the first fails.
You can wrap those in an
if ()
to give you some flow-control: