Assigning STDERR to a variable in Ruby

The following lists a few ways to assign STDERR streams to variables in Ruby:

  1. $ result = %x[find . -name ruby -type f 2>&1]

assigns both STDERR and STDOUT to result. This might be useful, for example, when you want to capture the entire output of the command.

  1. $ result = %x[find . -name ruby -type f 2>&1 1>/dev/null]

redirects STDERR to STDOUT which will assign it to result and then discards the command’s STDOUT. This might be useful when you only care to capture any error generated by the command.

The examples above use the %x operator to run the commands. You also might find useful this summary of 6 Ways To Run Shell Commands In Ruby.

Posted on Mar 24, 2011 | filed under Ruby | 2 comments

Comments

Jack
Jack wrote on Feb 29, 2012:

Thanx for these hints. They will surely save my time.
Regards, Jack from <a href="http://www.intellectsoft.co.uk/android_application_development.html">android software development</a>

Join the Discussion

URLs and email addresses will be converted to links and line breaks will be converted to paragraphs. Your email address is used only to display your Gravatar, and will never be displayed.

All HTML tags are disabled, except for two exceptions:

To display formatted code, use the <code> tag. By default, code between the tags is interpreted as Ruby, however, you may use the format <code:language> to change the default interpreter. The languages currently supported are Ruby, C, HTML and Delphi.

Using the <quote> tag, you may highlight quoted text in a formatted box.

  verification text
  Please type the text you see in the image above:
  or