6 ways to invoke execution of shell commands in Ruby _ruby topics

Source: Internet
Author: User
Tags echo command stdin

Ruby gives us six ways to complete a task when we encounter the need to invoke the operating system shell command:

1.Exec Method:

The Kernel#exec method replaces the current process example by invoking the specified command:

Copy Code code as follows:

$ IRB
>> exec ' echo ' Hello $HOSTNAME '
Hello nate.local
$

It is noteworthy that the Exec method replaces the IRB process with the echo command, thereby exiting the IRB. The main downside is that you can't know from your Ruby script whether the command was a success or failure.

2.System method

The Kernel#system Method Action command Ibid, but it is running a child shell to avoid overwriting the current process. Returns true if the command executes successfully, otherwise returns false.

Copy Code code as follows:

$ IRB
>> system ' echo ' Hello $HOSTNAME '
Hello nate.local
=> true
>> system ' false '
=> false
>> puts $?
256
=> Nil
>>

3. Inverted quotation mark (Backticks,esc key below)

Copy Code code as follows:

$ IRB
>> today = ' Date '
=> "Mon Mar 18:15:35 PDT 2007n"
>> $?
=> #<process::status:pid=25827,exited (0) >
>> $? To_i
=> 0

This is the most common use of this method. It is also running in a child shell.

4.io#popen

Copy Code code as follows:

$ IRB
>> Io.popen ("date") {|f| puts f.gets}
Mon Mar 18:58:56 PDT 2007
=> Nil

5.open3#popen3

Copy Code code 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
=> "15n"

6.open4#popen4

Copy Code code as follows:

$ IRB
>> require "OPEN4"
=> true
>> PID, stdin, stdout, stderr = Open4::p open4 "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.