How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
original title: "Calling shell commands from Ruby"
How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
Come posso chiamare i comandi di shell dall'interno di un programma Ruby? Come posso quindi ottenere l'output di questi comandi in Ruby?
Questo è il riepilogo dopo la traduzione, se è necessario visualizzare la traduzione completa, fare clic sull'icona "traduci"
This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link.
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.Here are ways to execute a shell script:
Kernel#`
, commonly called backticks –`cmd`
This is like many other languages, including Bash, PHP, and Perl.
Returns the result (i.e. standard output) of the shell command.
Docs: http://ruby-doc.org/core/Kernel.html#method-i-60
Built-in syntax,
%x( cmd )
Following the
x
character is a delimiter, which can be any character. If the delimiter is one of the characters(
,[
,{
, or<
, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation#{ ... }
is allowed.Returns the result (i.e. standard output) of the shell command, just like the backticks.
Docs: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html
Kernel#system
Executes the given command in a subshell.
Returns
true
if the command was found and run successfully,false
otherwise.Docs: http://ruby-doc.org/core/Kernel.html#method-i-system
Kernel#exec
Replaces the current process by running the given external command.
Returns none, the current process is replaced and never continues.
Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec
Here's some extra advice:
$?
, which is the same as$CHILD_STATUS
, accesses the status of the last system executed command if you use the backticks,system()
or%x{}
. You can then access theexitstatus
andpid
properties:For more reading see:
Here's a flowchart based on this answer. See also, using
script
to emulate a terminal.The way I like to do this is using the
%x
literal, which makes it easy (and readable!) to use quotes in a command, like so:Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:
Here's the best article in my opinion about running shell scripts in Ruby: "6 Ways to Run Shell Commands in Ruby".
If you only need to get the output use backticks.
I needed more advanced stuff like STDOUT and STDERR so I used the Open4 gem. You have all the methods explained there.
My favourite is Open3
Some things to think about when choosing between these mechanisms are:
You may need anything from simple backticks (``), system(), and
IO.popen
to full-blownKernel.fork
/Kernel.exec
withIO.pipe
andIO.select
.You may also want to throw timeouts into the mix if a subprocess takes too long to execute.
Unfortunately, it very much depends.
One more option:
When you:
You can use shell redirection:
The
2>&1
syntax works across Linux, Mac and Windows since the early days of MS-DOS.I'm definitely not a Ruby expert, but I'll give it a shot:
You should also be able to do things like:
The answers above are already quite great, but I really want to share the following summary article: "6 Ways to Run Shell Commands in Ruby"
Basically, it tells us:
Kernel#exec
:system
and$?
:Backticks (`):
IO#popen
:Open3#popen3
-- stdlib:Open4#popen4
-- a gem:If you really need Bash, per the note in the "best" answer.
If you need to use Bash, insert
bash -c "your Bash-only command"
inside of your desired calling method.quick_output = system("ls -la")
quick_bash = system("bash -c 'ls -la'")
To test:
system("echo $SHELL") system('bash -c "echo $SHELL"')
Or if you are running an existing script file (eg
script_output = system("./my_script.sh")
) Ruby should honor the shebang, but you could always usesystem("bash ./my_script.sh")
to make sure (though there may be a slight overhead from/bin/sh
running/bin/bash
, you probably won't notice.You can also use the backtick operators (`), similar to Perl:
Handy if you need something simple.
Which method you want to use depends on exactly what you're trying to accomplish; check the docs for more details about the different methods.
easiest way is, for example:
Using the answers here and linked in Mihai's answer, I put together a function that meets these requirements:
As a bonus, this one will also return STDOUT in cases where the shell command exits successfully (0) and puts anything on STDOUT. In this manner, it differs from
system
, which simply returnstrue
in such cases.Code follows. The specific function is
system_quietly
:We can achieve it in multiple ways.
Using
Kernel#exec
, nothing after this command is executed:Using
backticks or %x
Using
Kernel#system
command, returnstrue
if successful,false
if unsuccessful and returnsnil
if command execution fails:Don't forget the
spawn
command to create a background process to execute the specified command. You can even wait for its completion using theProcess
class and the returnedpid
:The doc says: This method is similar to
#system
but it doesn't wait for the command to finish.If you have a more complex case than the common case (that can not be handled with
``
) then check outKernel.spawn()
here. This seems to be the most generic/full-featured provided by stock Ruby to execute external commands.E.g. you can use it to:
Official ruby documentation has good enough examples.
backticks ` method is the easiest one to call shell commands from ruby. It returns the result of the shell command.
Given a command eg attrib
I've found that while this method isn't as memorable as e.g. system("thecommand") or thecommand in backticks, a good thing about this method compared to other methods.. is e.g. backticks doesn't seem to let me 'puts' the command I run / store the command I want to run in a variable, and system("thecommand") doesn't seem to let me get the output. Whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.
https://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html
http://ruby-doc.org/stdlib-2.4.1/libdoc/open3/rdoc/Open3.html
Not really an answer but maybe someone will find this useful, and its regarding to this.
When using TK GUI on Windows, and u need to call shell commands from rubyw, u will always have an annoying cmd window popping up for less then a sec.
To avoid this u can use
or
Both will store ipconfig's output inside 'log.txt', but no windows will come up.
U will need to
require 'win32ole'
inside your script.system()
,exec()
andspawn()
will all pop up that annoying window when using TK and rubyw.Here's a cool one that I use in a ruby script on OS X (so that I can start a script and get an update even after toggling away from the window):