To get the output, use backticks: out = `ls` returns the command's stdout as a string, and $?.exitstatus holds its exit code. To just run it, use system("ls"), which prints straight to the terminal and returns true, false or nil. For stdout, stderr and the status separately, use Open3.capture3, and pass the command and its arguments as separate strings whenever any part comes from outside.
Ruby has several ways to run another program, and they differ in three things: whether you get the output back as a string, whether a shell sits between Ruby and the program, and whether Ruby keeps running afterwards. The sections below cover backticks and %x(), system, Open3, argument arrays and shell injection, exec and Process.spawn, and what happens when the command does not exist, then a table to pick from. The commands here are the small BusyBox tools on this page (echo, ls, printf, wc, sh). Each example runs on this page: hit Run, then edit the code and run it again.
1Backticks and %x(): capture the outputRecommended
A command between backticks runs through /bin/sh (Ruby starts it directly when the string has no shell characters such as | or ;), and the expression returns everything it wrote to stdout as one String, trailing newline included. %x() is the same operator with a delimiter you choose, handy when the command itself holds backticks or quotes. Both interpolate #{...} like a double-quoted string. They don't raise when the command fails: Ruby stores a Process::Status in the global $?, so check $?.exitstatus or $?.success? right after the call.
# Backticks run the command through /bin/sh and return its stdout out = `echo hello from the shell` p out puts out.chomp.upcase # %x() is the same thing with a delimiter you choose count = %x(echo one two three | wc -w) p count.to_i # Ruby interpolation works inside both name = "Ruby" puts `echo "Hi, #{name}"` # $? holds the status of the last child process `sh -c 'exit 3'` p $?.exitstatus p $?.success? # stderr is not captured: it goes straight through missing = `ls /no/such/dir` p missing p $?.exitstatus # Add 2>&1 to capture it in the string too p `ls /no/such/dir 2>&1`
Output
The result is "hello from the shell\n" with the newline, so call chomp (or strip) before you use it. A pipe works because the string goes to the shell: echo one two three | wc -w gives 3 after to_i. After sh -c 'exit 3', $?.exitstatus is 3 and $?.success? is false. The failing ls returns an empty string with exit status 1, and its error message shows up in the stderr panel, not in the string; with 2>&1 it lands in the string instead. Backticks take the whole command as one string, so never put input you don't control inside them (section 4).
2system: run it and check whether it worked
system runs the command and lets it write straight to your program's stdout and stderr; it returns only how the run went: true for exit status 0, false for any other status, and nil when the command could not be started. That is why "getting the output of system" doesn't work: there is no output to get. Use backticks or Open3 instead, or redirect the output into a file with the out: option. With exception: true (Ruby 2.6 and later), a failure raises instead of returning false or nil.
puts "Before system" # The command prints directly; system returns true or false ok = system("echo printed by echo") puts "After system, returned #{ok}" p system("true") p system("false") p $?.exitstatus # nil means the command could not be started at all p system("no_such_command") p $?.exitstatus # Send the output to a file instead of the screen system("echo saved to a file", out: "log.txt") p File.read("log.txt") # exception: true raises when the command fails begin system("sh -c 'exit 2'", exception: true) rescue RuntimeError => e puts "RuntimeError: #{e.message}" end
Output
The lines come out in program order: Before system, then the command's printed by echo, then After system. Ruby buffers puts output, but it flushes $stdout before it starts the child, so you don't need $stdout.flush here (you do before exec, see section 5). system("false") returns false with status 1; a command that does not exist returns nil, and $?.exitstatus is 127. The raised error reads Command failed with exit 2: sh -c 'exit 2'.
3Open3: stdout, stderr and the status apart
The open3 library from the standard library gives you everything backticks hide. Open3.capture3 returns three values: the stdout string, the stderr string and the Process::Status, with nothing written to the screen and no reliance on the global $?. Open3.capture2e merges stdout and stderr into one string, like 2>&1, and Open3.capture2 returns stdout only. All three take a stdin_data: string to feed the command's input, and all three accept the command as one string (through the shell) or as separate arguments (no shell).
require 'open3' # capture3: stdout, stderr and the status, each on its own cmd = "echo result; echo warning >&2; exit 4" out, err, status = Open3.capture3(cmd) p out p err p status.exitstatus p status.success? # capture2e: stdout and stderr merged into one string both, status = Open3.capture2e("sh", "-c", "echo out; echo err >&2") p both p status.success? # capture2 with stdin_data: feed the command its input words, _status = Open3.capture2("wc", "-w", stdin_data: "one two three") p words.to_i
Output
capture3 keeps the two streams apart: "result\n" and "warning\n", with exit status 4. Nothing appears in the stderr panel, because the warning was captured. capture2e returns "out\nerr\n" in one string, and wc -w counted the 3 words passed in with stdin_data:. Like backticks, Open3 doesn't raise on a non-zero exit, so check status.success?. If you come from Python, capture3 is the closest thing to subprocess.run(..., capture_output=True).
4Pass arguments as an array to avoid shell injection
When the command is one string, it is split into words at spaces, and a shell acts on ;, |, $ and quotes. Interpolate a file name with a space and the command gets two arguments; interpolate input with a ; and the shell runs a second command. Pass the program and each argument as separate strings instead: system, Open3, spawn and exec then start the program directly, and every argument arrives exactly as written. Backticks have no such form; use Open3.capture2 with separate arguments when you need the output. If you must build a shell string, escape each piece with shellescape from the shellwords library.
require 'open3' require 'shellwords' name = "my notes.txt" File.write(name, "hello\n") # One string: the shell splits the name at the space p system("ls #{name}") # Separate arguments: no shell, the name arrives intact p system("ls", name) text, _status = Open3.capture2("cat", name) p text # A ; in the input runs a second command through the shell input = "hi; echo INJECTED" system("echo #{input}") system("echo", input) # To build a shell string anyway, escape every piece puts "ls #{name.shellescape}" system("ls #{name.shellescape}")
Output
system("ls #{name}") returns false, and the stderr panel shows why: ls: my: No such file or directory and the same for notes.txt. The array form lists my notes.txt and returns true. With the ;, the one-string echo prints hi and then INJECTED from a second command, while the separate-argument form prints hi; echo INJECTED as plain text. In a real program that second command could be anything, so treat every string that comes from a user, a file or a request as an argument, never as part of the command. shellescape turns the name into my\ notes.txt.
5exec and Process.spawn
Process.spawn (or just spawn) starts the command and returns its process id at once, without waiting; Ruby keeps running, and you collect the exit status later with Process.wait (which sets $?) or Process.wait2 (which returns it). exec is the opposite extreme: it replaces the Ruby process with the command, so it never returns and no line after it runs. Use it at the end of a wrapper script that only prepares the environment and hands over.
# spawn starts the command and returns its pid right away pid = Process.spawn("echo from the child") Process.wait(pid) puts "child exited with #{$?.exitstatus}" pid = spawn("sh", "-c", "exit 7") _pid, status = Process.wait2(pid) puts "second child exited with #{status.exitstatus}" # exec replaces this Ruby process with the command puts "about to exec" $stdout.flush exec("echo", "echo now owns the process") puts "this line is never printed"
Output
this line is never printed is indeed missing: after exec the process is echo, and the program's exit status is echo's. The $stdout.flush matters. exec does not flush Ruby's output buffer, so without it about to exec is lost and the run prints only echo now owns the process. Setting $stdout.sync = true at the top of a script has the same effect for every line. Always wait for a spawned child; one you never wait for keeps running on its own and its status is never collected.
6When the command does not exist
A command that isn't installed fails in one of two ways, depending on whether a shell is involved. Without a shell (separate arguments, or a single string with no shell characters, which Ruby runs directly), Ruby itself can't start the program and raises Errno::ENOENT from backticks and Open3; system returns nil unless you pass exception: true. Through a shell, the shell starts fine, prints its own error and exits with status 127.
require 'open3' # No shell: Ruby cannot start the program and raises begin `no_such_tool --version` rescue Errno::ENOENT => e puts "#{e.class}: #{e.message}" end begin Open3.capture3("no_such_tool", "--version") rescue Errno::ENOENT => e puts "#{e.class}: #{e.message}" end begin system("no_such_tool", exception: true) rescue Errno::ENOENT => e puts "#{e.class}: #{e.message}" end # Through a shell (here because of 2>&1) it is exit status 127 out = `no_such_tool --version 2>&1` p out p $?.exitstatus # Check first: command -v succeeds only for a command that exists p system("command -v ls > /dev/null") p system("command -v no_such_tool > /dev/null")
Output
All three direct calls raise Errno::ENOENT: No such file or directory - no_such_tool, so a script that shells out to an optional tool should rescue it. With 2>&1 in the string, a shell runs instead and reports "sh: no_such_tool: not found\n" with status 127, and nothing is raised. command -v is the portable shell way to test whether a command exists before you rely on it: it printed true for ls and false for the missing tool.
7Which should you use?
| Method | Returns | Separate arguments (no shell) | Best for |
|---|---|---|---|
| `cmd` / %x(cmd) | stdout as a String | No, one string only | Output of a fixed command |
| system(cmd) | true / false / nil | Yes | Run for the effect, check success |
| Open3.capture3 | out, err, status | Yes | Output and errors, outside input |
| Open3.capture2e | out + err, status | Yes | One combined log |
| Process.spawn | pid (wait for status) | Yes | Run while Ruby keeps working |
| exec(cmd) | Never returns | Yes | Hand the process over to a command |
Frequently asked questions
What is the difference between exec, system and backticks in Ruby?
Backticks (and %x()) run the command, through a shell when it has shell characters, wait for it and return its stdout as a string. system waits too but lets the command print directly and returns true, false or nil. exec replaces the Ruby process with the command, so it never returns and nothing after it runs. Backticks take the whole command as one string; system and exec also accept the program and its arguments as separate strings, which skips it.
How do I get the output of a system() call in Ruby?
You can't: system returns only true, false or nil, and the output goes straight to stdout. Use backticks or their %x() form, out = %x(cmd), for stdout as a string, or Open3.capture3(cmd) for stdout, stderr and the status separately. To keep system, redirect with system(cmd, out: "log.txt") and read the file afterwards.
How do I get the exit code of a shell command in Ruby?
After backticks, system or Process.wait, the global $? holds a Process::Status: $?.exitstatus is the code and $?.success? is true for 0. Process.last_status returns the same object, and require 'English' adds the readable alias $CHILD_STATUS. With Open3.capture3, use the status it returns. A command the shell cannot find gives 127.
How do I capture stderr from a shell command in Ruby?
Backticks capture stdout only. Use out, err, status = Open3.capture3(cmd) to get stderr as its own string, or Open3.capture2e(cmd) to get both streams merged. In a shell string you can also append 2>&1 to send stderr into the stdout that backticks capture.
Is it safe to interpolate variables into a shell command in Ruby?
Not when the value comes from outside your program. In %x(ls #{name}), in backticks or in system("ls #{name}"), the shell interprets spaces, ;, | and $ in name, so a value like x; rm -rf ~ runs a second command. Pass separate arguments instead, system("ls", name) or Open3.capture2("ls", name), or escape the value with name.shellescape after require 'shellwords'.
How do I run a command in the background in Ruby?
Use pid = Process.spawn(cmd): it starts the command and returns at once. Call Process.wait(pid) (or Process.wait2(pid), which also returns the status) when you need the result; for a child you never want to wait for, Process.detach(pid) collects its status in a background thread.
Can I use Ruby for shell scripting?
Yes. Start the file with #!/usr/bin/env ruby, read arguments from ARGV and input from $stdin, and end with exit 1 or abort("message") on failure. Ruby has built-in replacements for many commands, which are safer and portable: Dir.glob for ls, File.read for cat, and FileUtils.cp, mv, rm_rf and mkdir_p from the standard library. Shell out with system or Open3 for real external programs.