5

I can currently redirect stdout to a string variable in ruby/rails by simply running the command in bash and setting the result to my string variable as follows.

val = %x[ #{cmd} ]

where cmd is a string that represents a bash command.

However, this only captures stdout, for I want to capture stderr and set it to a string in ruby -- any ideas?

2 Answers 2

12

Simply redirect it:

val = %x[ #{cmd} 2>&1 ]

If you want to capture output from stderr only, close the file descriptor for stdout after copying it to fd 2.

val = %x[ #{cmd} 2>&1 >/dev/null ]
Sign up to request clarification or add additional context in comments.

1 Comment

Just one of those early morning questions that I really didn't think over more than once. :D
3

You can use Open3.popen3:

require 'open3'
stdin, stdout, stderr, wait_thread = Open3.popen3('ping -Z')
# => [#<IO:fd 9>, #<IO:fd 10>, #<IO:fd 12>, #<Thread:0x007fd3d30a0ce0 sleep>]

stderr.gets # => "ping: illegal option -- Z\n"
stdout.gets # => nil

1 Comment

Open3.capture3 might be a closer equivalent.

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.