Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting output of system() calls in Ruby

Tags:

ruby

system

call

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

system("ls") 
like image 687
Macha Avatar asked Mar 27 '09 15:03

Macha


People also ask

What is stdout in Ruby?

The $stdout is a global variable which holds the standard output stream. printing2.rb. #!/usr/bin/ruby $stdout.print "Ruby language\n" $stdout.puts "Python language" We print two lines using the $stdout variable. Ruby has another three methods for printing output.

What is system in Ruby?

The Ruby system method is the simplest way to run an external command. It looks like this: system("ls") Notice that system will print the command output as it happens. Also system will make your Ruby program wait until the command is done.

How do I run a shell command in Ruby?

First, note that when Ruby calls out to a shell, it typically calls /bin/sh , not Bash. Some Bash syntax is not supported by /bin/sh on all systems. This is like many other languages, including Bash, PHP, and Perl. Returns the result (i.e. standard output) of the shell command.


1 Answers

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 
like image 83
Craig Walker Avatar answered Sep 21 '22 11:09

Craig Walker