tags:

views:

6568

answers:

7

If I call a command using system() in ruby, how do I get it's output?

e.g.

system("ls")
+4  A: 

You use backticks:

`ls`
chaos
+1  A: 

You may want to have a look at this thread in comp.lang.ruby

Manrico Corazzi
+5  A: 

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.

dwc
+14  A: 

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
Craig Walker
what if I need to give a variable as part of my command? That is, what would something like system("ls " + filename) translate into when backticks are to be used?
Vijay Dev
You can do expression evaluation just as you would with regular strings: `ls #{filename}`.
Craig Walker
Hrm, makdown ate my formatting. There are back ticks ahead of the "l" in "ls" and after the "}" in "#{filename}".
Craig Walker
+2  A: 

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]
Geoff Wilson
Which is it? %w or %x? Or do they both work?
Platinum Azure
%x. I've updated the mistake above.
Geoff Wilson
+3  A: 

As a direct system(...) replacement you may use Open3.popen3(...)

Further discussion: http://tech.natemurray.com/2007/03/ruby-shell-commands.html

Darwin
A: 

just for the records, if you want both (output and operation result) you can do:

output=`ls no_existing_file` ;  result=$?.success?
FernandoFabreti