How to redirect a "system" standard output to a variable

Hi,

I need to redirect any standard output thrown when using a system call
into
a Ruby variable. I tried to search for a solution but couldn’t find
anything
that worked. May be I am not using the right search terms.

Here is what I am trying to do.

begin

rm somefile

end

If “somefile” doesn’t exist the OS throws the message “rm: cannot remove
`somefile’: No such file or directory” which I want to capture into a
variable.

Thanks,

On Nov 27, 3:58 pm, Venks [email protected] wrote:

begin

rm somefile

end

If “somefile” doesn’t exist the OS throws the message “rm: cannot remove
`somefile’: No such file or directory” which I want to capture into a
variable.

Thanks,

I use open4 for things like that. Try this it will show you how it
works.
http://codeforpeople.com/lib/ruby/open4/

test.rb

require ‘rubygems’
require ‘open4’

commands = [“rm somefile”,“ls”]
commands.each do |command|
status = Open4::popen4(command) do |pid,stdin,stdout,stderr|
puts “Running command: #{command}\n\n”
puts “pid:\n#{pid}”
puts “\nstdout:\n#{stdout.read.strip}”
puts “\nstderr:\n#{stderr.read.strip}”
end
puts “\nexitcode\n#{status.exitstatus}\n”
puts “----------\n\n\n”
end

$ ruby test.rb
Running command: rm somefile

pid:
11207

stdout:

stderr:
rm: somefile: No such file or directory

exitcode
1

Running command: ls

pid:
11208

stdout:
test.rb

stderr:

exitcode
0

On Nov 27, 2007, at 3:58 PM, Venks wrote:

begin
Thanks,
sys_msg = rm /Users/Desktop/foo.txt 2>&1
sys_msg # => “rm: /Users/Desktop/foo.txt: No such file or directory\n”

Regards, Morton