From: Robert Klemme Date: 2008-08-13T15:42:32+09:00 Subject: Re: File redirects in Ruby? Was Re: Sigh! I'm depressed. Debian vs Rubyand the backtick and subshells On 12.08.2008 22:55, John Carter wrote: > Anyone have a short and easy Ruby way of doing file redirects? Well, define it once and include it in all scripts where you need it. For example: robert@fussel /cygdrive/c/Temp $ ./redir.rb Done # Done # robert@fussel /cygdrive/c/Temp $ cat output drwx------+ 5 robert Kein 0 Aug 13 08:42 . robert@fussel /cygdrive/c/Temp $ cat output2 ls: cannot access does_not_exis: No such file or directory drwx------+ 5 robert Kein 0 Aug 13 08:42 . robert@fussel /cygdrive/c/Temp $ cat redir.rb #!/bin/env ruby module Kernel private def system_redir(args, fout = ::STDOUT, ferr = ::STDERR, fin = ::STDIN) child = fork do redir_fd ::STDIN, fin, "r" redir_fd ::STDOUT, fout, "w" redir_fd ::STDERR, ferr, "w" exec *args end Process.wait2(child).last end def redir_fd(io, target, mode = nil) case target when String io.reopen(File.open(target, mode)) when IO io.reopen target when io # do nothing when nil io.close else raise ArgumentError, "Invalid target argument #{target.inspect}" end end end res = system_redir %w{ls -ld}, "output" printf "Done %p\n", res File.open "output2", "w" do |io| res = system_redir %w{ls -ld . does_not_exis}, io, io printf "Done %p\n", res end robert@fussel /cygdrive/c/Temp Kind regards robert