Ruby Language Operating System or Shell commands

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

There are many ways to interact with the operating system. From within Ruby you can run shell/system commands or sub-processes.

Remarks

Exec:
Exec is very limited in functionality and when executed will exit the Ruby program and run the command.

The System Command:
The System command runs in a sub-shell instead of replacing the current process and returns true or nill. The system command is, like backticks, a blocking operation where the main application waits until the result of the system operation completes. Here the main operation never needs to worry about capturing an exception raised from the child process.

The output of system function will always be true or nil depending on whether or not the script has been executed without error. Therefore, every error while executing the script will not be passed to our application. The main operation never needs to worry about capturing an exception raised from the child process. In this case the output is nil because the child process raised an exception.
This is a blocking operation where the Ruby program will wait until the operation of the command completes before going on.
The system operation use fork to fork the current process and then execute the given operation using exec.

The backticks (`):
The backtick character is usualy located under the escape key on the keyboard. Backticks runs in a sub-shell instead of replacing the current process and returns the result of the command.
Here we can get the output of the command but the program will crash when an exception is generated.
If there is an exception in the sub-process then that exception is given to the main process and the main process might terminate if exception is not handled. This is a blocking operation where the Ruby program will wait until the operation of the command completes before going on.
The system operation use fork to fork the current process and then execute the given operation using exec.

IO.popen:
IO.popen runs in a sub-process. Here the sub-process standard input and standard output are connected to the IO object.

Popen3:
Popen3 allows you to access the standard input, standard output and standard error.
The subprocess's standard input and output will be returned into IO objects.

$? (same as $CHILD_STATUS)
Can be used with the backticks, system() or %x{} operations and will give the status of the last system executed command.
This might be usefull to access the exitstatus and the pid properties.

$?.exitstatus


Got any Ruby Language Question?