Six Methods for executing Linux shell commands in Ruby: rubyshell

Source: Internet
Author: User
Tags linux shell commands perl script

Six Methods for executing Linux shell commands in Ruby: rubyshell

In Ruby, executing shell commands is not surprising. Ruby provides about six methods for developers to implement. These methods are very simple. This article will introduce how to call terminal commands in a Ruby script.

Exec

Exec will replace the specified command with the operation in the current process. After the specified command ends, the process ends.

Copy codeThe Code is as follows:
Exec 'echo "hello world "'
Print 'abc'

Execute the preceding command and the result is as follows. We can see that there is no abc output. We can see that the process ends after the echo "hello world" command is executed. The print 'abc' following the execution will not continue '.

Copy codeThe Code is as follows:
Ruby testCommand. rb
Hello world

One headache with exec is that it is impossible to know whether the shell command is successfully executed or fails.

System

System is similar to exec, but the Command executed by system is not in the current process, but in a newly created process. System returns a Boolean value indicating whether the command execution result is successful or failed.

Copy codeThe Code is as follows:
$ Irb
> System 'echo "hello $ HOSTNAME "'
Hello androidyue
=> True
> Puts $?
Pid 11845 exit 0
=> Nil
> System 'false'
=> False
> Puts $?
Pid 11858 exit 1
=> Nil
>

System will assign the exit status code of the process to $ ?, If the program Exits normally, $? The value is 0, otherwise it is not 0. By checking the exit status code, we can throw an exception in the ruby script or retry the operation.

Note: In a Unix-like system, the exit status code of a process is 0 and non-0. 0 indicates success, and non-0 indicates failure.

System can tell us whether the command is successful or failed, but sometimes we need to get the output of the command and use it in the script. Obviously, the system cannot be directly satisfied. We need to use reverse quotation marks for implementation.

Back quotes (')

Using Reverse quotation marks is a common method in shell to get the output content of commands. It is also possible in ruby and must be changed at all times. If you run the command using backquotes, the command will also be executed in another process.

Copy codeThe Code is as follows:
1.9.3p448: 013> today = 'date'
=> "Sat Nov 15 19:28:55 CST 2014 \ n"
1.9.3p448: 014 >$?
### <Process: Status: pid 11925 exit 0>
1.9.3p448: 015 >$ ?. To_ I
=> 0
1.9.3p448: 016>

The above method is so simple that we can directly operate on the returned string results.

Note: $? It is no longer simply an exit Status code as described above. It is actually a Process: Status object. We can know not only the exit status code of the process, but also the process ID. Use $ ?. To_ I will get the exit status code, using $ ?. To_s will get a string containing the process id, exit Status Code, and other information.

One result of using backquotes is that we can only get the standard output (stdout) but not the standard error message (stderr). For example, in the following example, run a perl script that outputs an error string.

Copy codeThe Code is as follows:
$ Irb
> Warning = 'perl-e "Warn' dust in the wind '"'
Dust in the wind at-e line 1.
=> ""
> Puts warning

=> Nil

It can be seen that warning does not get the error information, which indicates that the standard error information cannot be obtained by quotation marks.

IO # popen

IO # popen is also a method for executing commands, and its commands are also executed in other processes. With popen, You can process standard input and output like an IO object.

Copy codeThe Code is as follows:
$ Irb
> IO. popen ("date") {| f | puts f. gets}
Mon Mar 18:58:56 PDT 2007
=> Nil

Open3 # popen3

Open3 is also provided in the standard Ruby library. Using this class, we can easily process standard input, output, and errors. Here we use an interactive tool dc. Dc is a counter of a non-Polish expression (also called a suffix expression, where each operator is placed after its operation object). It supports reading mathematical expressions from standard input. In this example, we apply two values and an operator to the pressure stack. Then use p to output the result. For example, input 5 and 10, input +, and then get the output of 15 \ n.

Copy codeThe Code is as follows:
$ Irb
> Stdin, stdout, stderr = Open3.popen3 ('dc ')
=> [# <IO: 0x6e5474>, # <IO: 0x6e5438>, # <IO: 0x6e53d4>]
> Stdin. puts (5)
=> Nil
> Stdin. puts (10)
=> Nil
> Stdin. puts ("+ ")
=> Nil
> Stdin. puts ("p ")
=> Nil
> Stdout. gets
=> "15 \ n"

Using this method, we can not only read the command output, but also input the command. This method is convenient for interactive operations. Through popen3, we can also get standard error messages.

Copy codeThe Code is as follows:
# (Irb continued ...)
> Stdin. puts ("asdfasdfasdfasdf ")
=> Nil
> Stderr. gets
=> "Dc: stack empty \ n"

However, popen3 has a defect in ruby 1.8.5, And the exit status of the process is not written to $? .

Copy codeThe Code is as follows:
$ Irb
> Require "open3"
=> True
> Stdin, stdout, stderr = Open3.popen3 ('false ')
=> [# <IO: 0x6f39c0>, # <IO: 0x6f3984>, # <IO: 0x6f3920>]
>>$?
==#< Process: Status: pid = 26285, exited (0)>
>>$ ?. To_ I
=> 0

The exit status after the command execution is 0 or false should be non-0. Due to this defect, we need to know about Open4.

Open4 # popen4

Open4 # popen4 is similar to Open3 # popen3, and we can also get the exit status of the program. Popen4 can also return a child process ID. You can also get the Process exit status through Process: waitpid2 and the corresponding Process ID. But the premise is to install the gem of open4.

Copy codeThe Code is as follows:
$ Irb
> Require "open4"
=> True
> Pid, stdin, stdout, stderr = Open4: popen4 "false"
=> [26327, # <IO: 0x6dff24>, # <IO: 0x6dfee8>, # <IO: 0x6dfe84>]
>>$?
=> Nil
> Pid
=> 26327
> Ignored, status = Process: waitpid2 pid
=> [26327, # <Process: Status: pid = 26327, exited (1)>]
> Status. to_ I
=> 256

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.