From: Brian Candler Date: 2007-05-13T03:30:09+09:00 Subject: Re: Writing A Ruby Shell On Sat, May 12, 2007 at 11:23:03PM +0900, Philip W. wrote: > I'm writing a Ruby shell for Ubuntu Linux 7.04. I would like my > shell to take commands from the user, run the command, output the result > to the command line, and log the result in a file. But I am having > trouble getting the Ruby shell to output the result to the command line, > and log the command. I've tried everything I can think of - using the > backticks method (``), exec(), system(), and IO.popen, strange > combinations of the mentioned and eval(), but nothing satisfies both of > my requirements. Sometimes the shell will output the command result to > the shell, but it won't log it. Sometimes it will log the command > result, but it won't output it to the shell. Sometimes it does one or > both things, but it only outputs or logs some of the command result. I > would appreciate any help that I could get on ways to make this work. Depending on what you're trying to do, the following might be useful: $ script log.txt $ irb ... do some stuff irb> quit $ exit $ cat log.txt If you want to take a single line of Ruby and execute it, then you can consider using eval(). Most Ruby code which writes to standard output actually uses the variable $stdout (similarly $stdin for input and $stderr for error messages), so you can reassign $stdout and $stderr to a different IO object (e.g. a StringIO) to catpure it. However, if the Ruby code you're running in turn runs some external system program, e.g. system("ls"), then that won't work. What you'd need to do then is to run the command in a completely separate process. Look at IO.popen("-"). Look at open3.rb in the standard library if you need to capture stderr as well. Regards, Brian.