Interpolated shell command

Since Ruby is scripting language, it offers different types to fire a shell command. One of them is the interpolated percentage notation. Basically the ‘%’ literal is characterized by:

  1. The command can be assigned as a String (or even without the String notation, meaning without quotation marks)
  2. Executes the command in a subshell
  3. Is a blocking operation (waits until the result of operation completes)
  4. Returns the command result
  5. Raises exception caused by the child process error
  6. The error status (exception) is available in $?, which returns a Process::Status object (with qualified exit status)

Some examples.
As a start a script.rb file is assumed. It can be found with the shell command ‘find’:

%x{find *.rb} # => "script.rb"

But if the file name has to be interpolated, it can be achieved easily:

name = 'script'
%x{find #{name}.rb} # => "script.rb"

The UNIX shell command ‘date’ returns the system time. It can be parsed into a Time object by Ruby afterwards:

Time.parse %x{date}.chop # => 2014-10-10 02:23:10 +0200

Or just watching it sleeping:

(0..4).each { |seconds| puts %x{ sleep #{seconds} && 'date'} }

An unknown command raises an error, which is returned:

%x{foo} # => Errno::ENOENT: No such file or directory - foo

and even can be processed afterwards:

$? # => #<Process::Status: pid 4357 exit 127>
$?.exitstatus # => 127