liveBook · Manning

System method

As explained in The Well-Grounded Rubyist, Fourth Edition

The system method is a Ruby method that executes an external command through the host operating system and reports whether it succeeded.

Ruby’s system method runs an external program through the host operating system. Pass the program name and any arguments; the child process uses the current STDIN, STDOUT, and STDERR. section 14.6.1

Run a command

system("date") prints the command’s output and returns true when the command exits successfully. A command such as grep can read directly from the terminal until end-of-file, then return false when its search finds no match. section 14.6.1

The return value distinguishes several outcomes:

  • The thread-local global variable $? receives a Process::Status object containing the child process ID and exit status. section 14.6.1

Use system when the command should communicate through the existing terminal streams and Ruby mainly needs to know whether it succeeded. Backticks serve a different purpose: they return the command’s output as a string while also setting $?. exec replaces the current Ruby process with the requested command. section 14.6.1

>> system("date")
Sun Apr 22 08:49:11 EDT 2018
=> true
>> $?
=> #<Process::Status: pid 28025 exit 0>
>> system('grep "D"')
^d=> false
>> $?
=> #<Process::Status: pid 28026 exit 1>

Compare a successful date command with grep’s nonzero exit status and inspect the resulting Process::Status objects. section 14.6.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains invocation, return values, Process::Status, thread-local $?, and contrasts backticks and exec; it defers lower-level facilities.
Examples
Uses date, cat, grep, nonexistent commands, thread-local status, and captured backtick output.
What you can do after
Operate/configure external commands and diagnose success, failure, missing programs, and exit status from Ruby.
How it connects
Connects external programs with standard streams, Process::Status, threads, backticks, and exec.

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.