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
