Assigning STDERR to a variable in Ruby
The following lists a few ways to assign STDERR streams to variables in Ruby:
- $ 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.
- $ 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
