If I call a command using Kernel#system in Ruby, how do I get its output?
system("ls")
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With