Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can an external command return both its output and its exit status to Ruby?

This is a follow up question regarding ruby system command check exit code. I want to run command such that to get its output as well as exit code. Currently what I used in the code is:

rv = `#{cmd} 2>&1`

But this only captures output, and

rv = system(cmd)

only captures the exit code. How to achieve both?

like image 506
user180574 Avatar asked Jan 23 '14 01:01

user180574


People also ask

What are Backticks in Ruby?

Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.

How do I run a shell script in Ruby?

Create configurations for script files and select Shell Script. Under Execute, select the Script file option. Specify the path to the script file and options that you want to pass to the script when it is launched.

What is a ruby system?

The Ruby system method is the simplest way to run an external command. It looks like this: system("ls") Notice that system will print the command output as it happens. Also system will make your Ruby program wait until the command is done.


2 Answers

Check $?.exitstatus for the exit code.

For more info, see http://www.ruby-doc.org/core-2.1.0/Process/Status.html

like image 137
Matt Avatar answered Nov 15 '22 14:11

Matt


Backticks will capture the output from your command. For example, to store the output in the rv variable:

rv = `echo Error: EX_USAGE; exit 64`
#=> "Error: EX_USAGE\n"

You can interrogate the exit status of the process from the built-in $? variable or from a Process::Status object. For example, to get the exit status of the last backtick command:

$?.exitstatus
#=> 64
like image 28
Todd A. Jacobs Avatar answered Nov 15 '22 15:11

Todd A. Jacobs