End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Kernel#system
static VALUE
rb_f_system(int argc, VALUE *argv, VALUE _)
{
VALUE execarg_obj = rb_execarg_new(argc, argv, TRUE, TRUE);
struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
struct rb_process_status status = {0};
eargp->status = &status;
rb_last_status_clear();
// This function can set the thread's last status.
// May be different from waitpid_state.pid on exec failure.
rb_pid_t pid = rb_execarg_spawn(execarg_obj, 0, 0);
if (pid > 0) {
VALUE status = rb_process_status_wait(pid, 0);
struct rb_process_status *data = RTYPEDDATA_DATA(status);
// Set the last status:
rb_obj_freeze(status);
GET_THREAD()->last_status = status;
if (data->status == EXIT_SUCCESS) {
return Qtrue;
}
if (data->error != 0) {
if (eargp->exception) {
VALUE command = eargp->invoke.sh.shell_script;
RB_GC_GUARD(execarg_obj);
rb_syserr_fail_str(data->error, command);
}
else {
return Qnil;
}
}
else if (eargp->exception) {
VALUE command = eargp->invoke.sh.shell_script;
VALUE str = rb_str_new_cstr("Command failed with");
rb_str_cat_cstr(pst_message_status(str, data->status), ": ");
rb_str_append(str, command);
RB_GC_GUARD(execarg_obj);
rb_exc_raise(rb_exc_new_str(rb_eRuntimeError, str));
}
else {
return Qfalse;
}
RB_GC_GUARD(status);
}
if (eargp->exception) {
VALUE command = eargp->invoke.sh.shell_script;
RB_GC_GUARD(execarg_obj);
rb_syserr_fail_str(errno, command);
}
else {
return Qnil;
}
}
Executes command… in a subshell. command… is one of following forms.
commandline-
command line string which is passed to the standard shell
cmdname, arg1, ...-
command name and one or more arguments (no shell)
[cmdname, argv0], arg1, ...-
command name,
argv[0]and zero or more arguments (no shell)
system returns true if the command gives zero exit status, false for non zero exit status. Returns nil if command execution fails. An error status is available in $?.
If the exception: true argument is passed, the method raises an exception instead of returning false or nil.
The arguments are processed in the same way as for Kernel#spawn.
The hash arguments, env and options, are same as exec and spawn. See Kernel#spawn for details.
system("echo *") system("echo", "*")
produces:
config.h main.rb *
Error handling:
system("cat nonexistent.txt") # => false system("catt nonexistent.txt") # => nil system("cat nonexistent.txt", exception: true) # RuntimeError (Command failed with exit 1: cat) system("catt nonexistent.txt", exception: true) # Errno::ENOENT (No such file or directory - catt)
See Kernel#exec for the standard shell.