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
