9

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?

3 Answers 3

8

Check $?.exitstatus for the exit code.

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

$? accesses the status of the last system executed command if you use the backticks, system() or %{}. You can then access the exitstatus and pid properties.

Source

So you can do rv = system(cmd), and do status = $?.exitstatus.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.