How to call shell commands from Ruby

ID : 1079

viewed : 161

Tags : rubyshellinteropruby

Top 5 Answer for How to call shell commands from Ruby

vote vote


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:

cmd = "echo 'hi'" # Sample string that can be used 
  1. 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.


    value = `echo 'hi'` value = `#{cmd}` 
  2. 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.


    value = %x( echo 'hi' ) value = %x[ #{cmd} ] 
  3. Kernel#system

    Executes the given command in a subshell.

    Returns true if the command was found and run successfully, false otherwise.


    wasGood = system( "echo 'hi'" ) wasGood = system( cmd ) 
  4. Kernel#exec

    Replaces the current process by running the given external command.

    Returns none, the current process is replaced and never continues.


    exec( "echo 'hi'" ) exec( cmd ) # Note: this will never be reached because of the line above 

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 the exitstatus and pid properties:


For more reading see:

vote vote


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:

directorylist = %x[find . -name '*test.rb' | sort] 

Which, in this case, will populate file list with all test files under the current directory, which you can process as expected:

directorylist.each do |filename|   filename.chomp!   # work with file end 
vote vote


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.

vote vote


My favourite is Open3

  require "open3"    Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... } 

Top 3 video Explaining How to call shell commands from Ruby