Getting output of system() calls in Ruby

Macha picture Macha · Mar 27, 2009 · Viewed 261.1k times · Source

If I call a command using Kernel#system in Ruby, how do I get its output?

system("ls")

Answer

Craig Walker picture Craig Walker · Oct 14, 2009

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

or

printf output # escapes newline chars