Ruby System Command Return Code

I have a bunch of ruby ​​system calls, such as the following, and I want to check their exit codes at the same time so that my script exits if this command fails.

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

I need something like

system("VBoxManage createvm --name test1", 0) <- where the second parameter checks the exit code and confirms that this system call was successful, and if not, it will cause an error or do something like that.

Is this even possible?

I tried something about this, and it 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 
+71
ruby command exit-code exit
Sep 10 '13 at 20:22
source share
5 answers

From the documentation :

System

returns true if the command gives a 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 

Further

Error status available in $? .

 system("VBoxManage createvm --invalid-option") $? #=> #<Process::Status: pid 9926 exit 2> $?.exitstatus #=> 2 
+125
Sep 10 '13 at 20:31 on
source share

system returns false if the command has a nonzero 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 be brief enough.

+20
Sep 10 '13 at 20:26
source share

For me, I preferred to use `` to invoke shell commands and check $? to get the status of the process. $? is a process status object, you can get information about the process from this object, including: status code, execution status, pid, etc.

Some useful $ methods? An object:

  $?.exitstatus => return error code $?.success? => return true if error code is 0, otherwise false $?.pid => created process pid 
+13
Jul 31 '16 at 11:17
source share

You do not record the result of your call to system , into which the returned code is returned:

 exit_code = system("ruby test.rb") 

Remember that every call to system or its equivalent, which includes the backtick-method, spawns a new shell, so it is impossible to get the result of the previous shell. In this case, exit_code true if everything worked, nil otherwise.

The popen3 command provides more detailed lower-level information.

+5
Sep 10 '13 at 20:26
source share

One way to do this is to bind them with and or && :

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

The second call will not start if the first fails.

You can wrap them in if () to give you some flow control:

 if ( system("VBoxManage createvm --name test1") && system("ruby test.rb") ) # do something else # do something with $? end 
+3
Sep 10 '13 at 21:43
source share



All Articles