Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Process.exec

exec([env, ] command_line, options = {})
exec([env, ] exe_path, *args, options = {})

Replaces the current process by doing one of the following:

  • Passing string command_line to the shell.

  • Invoking the executable at exe_path.

This method has potential security vulnerabilities if called with untrusted input; see Command Injection.

The new process is created using the exec system call; it may inherit some of its environment from the calling program (possibly including open file descriptors).

Argument env, if given, is a hash that affects ENV for the new process; see Execution Environment.

Argument options is a hash of options for the new process; see Execution Options.

The first required argument is one of the following:

  • command_line if it is a string, and if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters.

  • exe_path otherwise.

Argument command_line

String argument command_line is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:

Example
exec('if true; then echo "Foo"; fi') # Shell reserved word.
exec('echo')                         # Built-in.
exec('date > date.tmp')              # Contains meta character.

The command line may also contain arguments and options for the command:

Example
exec('echo "Foo"')

Output:

Example
Foo

See Execution Shell for details about the shell.

Raises an exception if the new process could not execute.

Argument exe_path

Argument exe_path is one of the following:

  • The string path to an executable to be called.

  • A 2-element array containing the path to an executable and the string to be used as the name of the executing process.

Example:

Example
exec('/usr/bin/date')

Output:

Sat Aug 26 09:38:00 AM CDT 2023

Ruby invokes the executable directly, with no shell and no shell expansion:

Example
exec('doesnt_exist') # Raises Errno::ENOENT

If one or more args is given, each is an argument or option to be passed to the executable:

Example
exec('echo', 'C*')
exec('echo', 'hello', 'world')

Output:

C*
hello world

Raises an exception if the new process could not execute.

See also .euid= .exit .euid .exit! also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0