Open In App

How to execute shell command in Ruby?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Ruby is also known for its simplicity and versatile nature, it provides various methods for executing shell commands within your scripts. Whether you need to interact with the underlying operating system or automate tasks, Ruby offers several approaches to seamlessly integrate shell commands into your codebase. In this article, we’ll explore these methods and discuss their use cases and nuances.

Methods to execute shell commands in ruby

1. Backticks (…) or %x{} Syntax:

One of the simplest ways to execute shell commands in Ruby is by using backticks or the `%x{}` syntax. This method captures the standard output of the command and returns it as a string.

Ruby
result = `ls -l`
puts result

Here, the command `ls -l` is executed, and the resulting output is stored in the variable result and printed to the console.

2. Kernel#system

The system method executes the given command in a subshell. It returns true if the command was successful and false otherwise.

Ruby
success = system("ls -l")
puts success # prints true or false

This method is suitable for simple command execution and checking the success status.

3. Kernel#exec

Unlike `system`, the` exec` method replaces the current process by running the given command. It does not return to the calling Ruby script unless the command fails.

Ruby
exec("ls -l")
puts "This line won't be executed"

When using `exec`, be aware that the script terminates after the command is executed, and subsequent code is not reached.

4. IO.popen

For more control over input and output streams, you can use` IO.popen`. This method opens a pipe to or from a command, allowing you to interact with its input and output

Ruby
IO.popen("ls -l") do |io|
  puts io.read
end

Here, the `ls -l` command’s output is captured and printed to the console within the block.

5. Open3 Module

For advanced features such as capturing output and handling errors, the `Open3` module is a powerful tool. It provides methods like `Open3.capture3`, which captures the standard output, standard error, and status of the executed command.

Ruby
require 'open3'
stdout, stderr, status = Open3.capture3('ls -l')
puts stdout

Utilizing `Open3` is beneficial when you require more granular control over subprocesses and need to handle errors robustly.

Conclusion

In Ruby, executing shell commands is a straightforward task thanks to its rich set of built-in methods and modules. Whether you need basic command execution, input/output stream control, or advanced error handling, Ruby offers the flexibility to meet your requirements. By understanding the nuances of each method, you can choose the most suitable approach for your specific use case, empowering you to leverage the full potential of Ruby in your shell scripting endeavors.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads