If I call a command using system() in ruby, how do I get it's output?
e.g.
system("ls")
If I call a command using system() in ruby, how do I get it's output?
e.g.
system("ls")
You may want to have a look at this thread in comp.lang.ruby
Another way is:
f = open("|ls")
foo = f.read()
Note that's the "pipe" character before "ls" in open. This can also be used to feed data into the programs standard input as well as reading its standard output.
I'd like to expand & clarify chaos's answer a bit.
If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:
output = `ls`
p output
I found that the following is useful if you need the return value:
result = %x[ls]
puts result
I specifically wanted to list the pids of all the Java processes on my machine, and used this:
ids = %x[ps ax | grep java | awk '{ print $1 }' | xargs]
As a direct system(...) replacement you may use Open3.popen3(...)
Further discussion: http://tech.natemurray.com/2007/03/ruby-shell-commands.html
just for the records, if you want both (output and operation result) you can do:
output=`ls no_existing_file` ; result=$?.success?