Overview
Ruby’s system method can be used to run system commands in Ruby. Below is the syntax for the same
system(some_command)
Some important points to note about system command
- It will wait until the command is executed
- It will return true if the command is a success
- It will return false if the command is a failure and returns an error code
- It will return nil if the command is not found
Let’s check out a program for the same
Program
output = system("pwd")
puts "For pwd command: " + output.to_s
output = system("exit 1")
puts "For exit 1 command: " + output.to_s
output = system("pwd1")
puts "For pwd1 command: " + output.to_s
Output
<current_directory>
For pwd command: true
For exit 1 command: false
For pwd1 command:
In the above program, there are three cases
- When the command is a success
output = system("pwd")
puts "For pwd command: " + output.to_s
The output, in this case, is true
<current_directory>
For pwd command: true
- When the command is a failure
output = system("exit 1")
puts "For exit 1 command: " + output.to_s
The output, in this case, is false
For exit 1 command: false
- When the command doesn’t exist i.e pwd1 is an invalid command
output = system("pwd1")
puts "For pwd1 command: " + output.to_s
The output, in this case, is nil
For pwd1 command: