liveBook · Manning

Backticks

As explained in The Well-Grounded Rubyist, Fourth Edition

Backticks are Ruby syntax for executing an external command and returning its standard output as a string.

Ruby backticks execute an external command and return its standard output as a string. Unlike system, they capture output instead of sending it directly to the usual streams. section 14.6.1

Capture command output

d = `date` assigns the command's output, including its trailing newline, to d. Running `cat` similarly places everything cat produces into a variable rather than echoing it immediately. section 14.6.1

Backticks also set $? to a Process::Status object, just as system does. A successful command produces output and an exit status of zero; a nonexistent command raises Errno::ENOENT while still updating $?. section 14.6.1

Choose the related execution form according to the result you need:

  • Use system when the external program should use Ruby's current STDIN, STDOUT, and STDERR and return success information. section 14.6.1
  • Use exec when the current process should be replaced by the command's process. section 14.6.1
  • Use %x when command interpolation or an alternate delimiter makes the command expression easier to write. section 14.6.1
>> d = `date`
=> "Tue Sep 23 14:59:54 EDT 2025\n"
>> puts d
Tue Sep 23 14:59:54 EDT 2025
=> nil
>> output = `cat`
I'm typing into cat. Since I'm using backticks,
I won't see each line echoed back as I type it.
Instead, cat's output is going into the
variable output. 
=> "I'm typing into cat. Since I'm using backticks,\nI won't etc.
>> puts output
I'm typing into cat. Since I'm using backticks,
I won't see each line echoed back as I type it.
Instead, cat's output is going into the
variable output.

Compare direct command output with output captured in variables. section 14.6.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains syntax, captured output, exit status, and missing-command behavior, but only briefly surveys lower-level alternatives.
Examples
Demonstrates date and cat commands, captured variables, nonexistent commands, and inspection of $?.
What it assumes
Assumes basic Ruby expressions and variables while introducing system commands, standard streams, and process status.
What you can do after
Apply it to run an external command, capture its standard output, and inspect the resulting process status.
How it connects
Connects backticks with system, exec, %x, Process::Status, standard streams, and external programs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.