Calling the OS

Ruby supports a number of global functions for interacting with the operating system to execute programs, fork new processes, handle signals, and so on. Ruby was initially developed for Unix-like operating systems, and many of these OS-related functions reflect that heritage. By their very nature, these functions are less portable than most others, and some may not be implemented at all on Windows and other non-Unix platforms. The subsections that follow describe some of the most commonly used of the OS-dependent functions. Functions, such a syscall, that are particularly low-level or platform-dependent are not covered here.

Invoking OS Commands

The Kernel.` method expects a single string argument representing an OS shell command. It starts a subshell and passes the specified text to it. The return value is the text printed to standard output. This method is typically invoked using special syntax; it is invoked on string literals surrounded by backquotes or on string literals delimited with %x (see Backtick command execution). For example:

os = `uname`             # String literal and method invocation in one
os = %x{uname}           # Another quoting syntax
os = Kernel.`("uname")   # Invoke the method explicitly

This method does not simply invoke the specified executable; it invokes a shell, which means that shell features such as filename wildcard expansion are available:

files = `echo *.xml`

Another way to start a process and read its output is with the Kernel.open function. This method is ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.