ruby system command check exit code ruby system command check exit code ruby ruby

ruby system command check exit code


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")     #=> nilsystem("echo foo")            #=> truesystem("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


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:

   $?.exitstatus => return error code       $?.success? => return true if error code is 0, otherwise false   $?.pid => created process pid


system returns false if the command has an non-zero exit code, or nil if there is no command.

Therefore

system( "foo" ) or exit

or

system( "foo" ) or raise "Something went wrong with foo"

should work, and are reasonably concise.