Six methods Ruby shell calls

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
When need to call the operating system shell command, Ruby provides six methods to complete the task for us:
The 1.Exec method:
Kernel#Exec method replaces the current process by invoking the specified command:
Example:
$ irb
>> exec 'echo "hello $HOSTNAME"'
hello nate.local
$
valueIt is noteworthy, the exec method using the echo command to replace the IRB process to exit irb. The major drawback is, you can't from your ruby scripts that this command is success or failure.

The 2.System method.
Kernel#System command again, but it was running a sub shell to avoid overwriting the current process. If the successful execution of true is returned, otherwise it returns false.

$ irb
>> system 'echo "hello $HOSTNAME"'
hello nate.local
=> true
>> system 'false'
=> false
>> puts $?
256
=> nil
>>
3 reverse quotes (Backticks, Esc key the key)
$ irb
>> today = `date`
=> "Mon Mar 12 18:15:35 PDT 2007n"
>> $?
=> #<Process::Status: pid=25827,exited(0)>
>> $?.to_i
=> 0
This method is the most common usage. It also works in a subset of shell.
4.IO#popen
$ irb
>> IO.popen("date") { |f| puts f.gets }
Mon Mar 12 18:58:56 PDT 2007
=> nil
5.open3#popen3
$ 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
$ 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





This article from the "Enlightenment" blog, please keep the source

Call shell command in ruby, you must know:
Ruby code
%x{'command'}
command
%x{'command'}
command
Then can by $? For the operation of the state, is unable to get the error information operation after the failure of the.
Ruby code
require "open3"
stdin, stdout, stderr = Open3.popen3('command')
stdin.puts('')
stdout.gets
stderr.gets
require "open3"
stdin, stdout, stderr = Open3.popen3('command')
stdin.puts('')
stdout.gets
stderr.gets
Ha, you can capture the error information.
This intermediate is above URL contents
The ruby command line options are many, here will be explained in detail these options
Please use the following command to start the Ruby interpreter.
ruby [ option ...] [ -- ] [ programfile ] [ argument ...]
Here " option" that it will be mentioned in a command line options. " --" is explicitly indicated that option string to the end. " programfile" Ruby script file is loaded. If you omit or written as " -", Ruby will be the standard input as a Ruby script processing.
Programfile if the "#!", to carry out special treatment. Details please refer to the following bank about interpreter.
The initial value strings in argument will become the internal constant ARGV;. In some environments (Win32), standard shell does not expand wildcards, then the Ruby interpreter will automatically spread wildcards and Fu value ARGV. At this time, can use wildcard characters ","? "," [] "and" * "(unlike Dir.glob, you can't use" {..} "). In the Win32 environment, if you do not want to show the opening matches with the words, please use single quotes (') parameters including.
Command line options
The Ruby interpreter can accept the following command line options. Basically with Perl classlike.
-0 digital
Specify 8 hexadecimal number input record separator('$/').
If you do not specify the number of words, the delimiter is null character (equivalent to $/=" If you do not specify the number of words, the delimiter is null character (equivalent to $/=" 若不指定数字的话, 分隔符是空字符(等同于$/="\0"). 数字后面可以有其他的开关"). Behind the numbers can have other switch"). Behind the numbers can have other switch(switch).
-00 represents the paragraph mode (equivalent to $/=" "), -0777 (because the code does not represent any text) said it will all the content of the document (the equivalent loads$/=nil).
-a
Used together with'-n'or'-p', you can open automatically split mode (auto split mode). Automatic resolution mode will perform the following actions before each cycle.
$F = $_.split
Without specifying the'-n'or'-p' option will not work.
-C directory
Execute the script before, first moved to the specified directory.
-c
Only the script compiler, and does not perform. After the compiler if no syntax errors are found, then display"Syntax OK".
--copyright
Display a copyright information.
-Kc
Specify Ruby to Chinese characters code processing. If'E'or'e', Ruby identified Chinese characters encoded string or access the file for the EUC. Similarly, if'S'or's' is identified as SJIS. If the'U'or'u' as a UTF-8. 'N'said the wrong Chinese characters processing. This option is the default value N(NONE).
Can change text encoding approach in the future, then this option content will vary.
-d --debug
Execute the script in debug mode. Set the $DEBUG true.
-e script
Specify the script on the command line. Add the -e option, would not be drawn from the script file parameters.
If the times when you use the -e option, the system will deal with it in the following way.
Each of the following expressions of the same meaning. ruby -e "5.times do |i|" -e "puts i" -e "end" ruby -e "5.times do |i| puts i end" ruby -e "5.times do |i|; puts i; end" -Fregexp
Specify regexp to enter the field separator(field separator).
-h --help
Display command line options.
-i[extension]
The parameters specified in the contents of the file are replaced (in-place edit). The original file will be added to the extension and preserved. If no extension of words, will not back up, and only the replacement file will be retained.
An example:
% echo matz > /tmp/junk % cat /tmp/junk matz % ruby -p -i.bak -e '$_.upcase!' /tmp/junk % cat /tmp/junk MATZ % cat /tmp/junk.bak matz -I directory
The specified path loading file (additional). The specified directory is appended to the Ruby array variable ($:).
-l
Automatic processing line. First of all, will $\ to $/ value add newlines, in the print output. If using the -n logo or logo -p words, will the end of the gets read String#chop processing line!.
-n
If the use of the mark, the entire program like sed -n or awk, is
while gets ... end
Including the operation.
-p
With -n logo is similar, the output variables in each cycle of the $_value.
An example:
% echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"' MATZ -r feature
Execute the script, the first implementation of require operation on the specified database feature. Used together with the'-n'option, the'-p' option especially useful.
-s
To explain to the script name and parameters' - 'at the beginning, and the Fu value value to the same name as a global variable. Encountered with the parameters'--'first stop to explain, and remove the parameters from the ARGV.
An example:

! /usr/local/bin/ruby -s # prints "true" if invoked with `-xyz' switch. print "true\n" if $xyz -S

This option shows that, when the script name not to '/' at the beginning, to use the environment variable PATH value search script. If your machine does not support #! So, you can use the following method to simulate the operation of #!:

!/bin/sh exec ruby -S -x $0 "$@" #! ruby

Because the relationship of the first elements, the script to /bin/sh system. /bin/sh implementation of line second to start the Ruby interpreter. In the -x options under the action of the Ruby interpreter, from'#! 'to a line containing'ruby' content of all read.
Depending on the system, Depending on the system, 根据系统的不同, $0未必包含完整路径, 因此有必要使用'-S'选项来告诉Ruby在必要时搜索脚本 may not include the full path, so it is necessary to use the'-S'option to tell the search script is necessary in Ruby may not include the full path, so it is necessary to use the'-S'option to tell the search script is necessary in Ruby.
-T[level]
The implementation is not tested for purity. If level specifies a value after that, the safety level will also use this value. Level is omitted, the value 1. For CGI application, the specified is suitable for -T1. The $SAFE class will also be set.
-v --verbose
Verbose mode. Display version information is started, then the internal variable $VERBOSE is set to true. When the variable is true, the method will display verbose information at run time. If only set the'-v'option, while none of the other parameters, after the launch will be the first display version information, and then the end of operation (not wait from standard input script).
--version
Display version information of Ruby.
-w
Do not display verbose version information.
-W[level]
Ruby 1.8 features
You can specify verbose mode of 3 level, as shown below.
-W0: does not display a warning -W1: only shows important warning (default) -W2 or -W: to display all warning
$VERBOSE internal variables are set to nil,false,true.
-x[directory]
Remove the script from the message and execution. Read the script from the scope of'#! 'start, until the'ruby' contains the behavior check. Using EOF (end of file), ^D (controlD), ^Z (controlZ) or the reserved word _END_ to specify the script ends.
If the specified directory name, then moved to the specified directory in the execution of the script before.
-y --yydebug
The compiler debugging mode. Show the process of parsing script is compiled. The display will be a long process, may be useful for those who want to debug the compiler.
About the interpreter for
The script is specified on the command line to'#! 'at the beginning of the file, if'ruby' does not contain the line, will replace the OS'#! The string 'back as the command line, and then start the interpreter.
For example, SH will start to run with Ruby following shell script.

!/bin/sh -vx echo "$@"

If it contains'ruby','ruby' on the left side of the part will be ignored, the right side was regarded as the option to '-' the beginning part.
This specifies options will be appended to the command line options specified. This is mainly to embed the specified in the script options. For example, the following function equivalent script to use the command line to specify the -Ke option.

! ruby -Ke

The article comes from
Please use the following command to start the Ruby interpreter.
ruby [ option ...] [ -- ] [ programfile ] [ argument ...]
Here " option" that it will be mentioned in a command line options. " --" is explicitly indicated that option string to the end. " programfile" Ruby script file is loaded. If you omit or written as " -", Ruby will be the standard input as a Ruby script processing.
Programfile if the "#!", to carry out special treatment. Details please refer to the following bank about interpreter.
The initial value strings in argument will become the internal constant ARGV;. In some environments (Win32), standard shell does not expand wildcards, then the Ruby interpreter will automatically spread wildcards and Fu value ARGV. At this time, can use wildcard characters ","? "," [] "and" * "(unlike Dir.glob, you can't use" {..} "). In the Win32 environment, if you do not want to show the opening matches with the words, please use single quotes (') parameters including.
Command line options
The Ruby interpreter can accept the following command line options. Basically with Perl classlike.
-0 digital
Specify 8 hexadecimal number input record separator('$/').
若不指定数字的话, 分隔符是空字符(等同于$/="\0"). 数字后面可以有其他的开关(switch).
-00 represents the paragraph mode (equivalent to $/=" "), -0777 (because the code does not represent any text) said it will all the content of the document (the equivalent loads$/=nil).
-a
Used together with'-n'or'-p', you can open automatically split mode (auto split mode). Automatic resolution mode will perform the following actions before each cycle.
$F = $_.split
Without specifying the'-n'or'-p' option will not work.
-C directory
Execute the script before, first moved to the specified directory.
-c
Only the script compiler, and does not perform. After the compiler if no syntax errors are found, then display"Syntax OK".
--copyright
Display a copyright information.
-Kc
Specify Ruby to Chinese characters code processing. If'E'or'e', Ruby identified Chinese characters encoded string or access the file for the EUC. Similarly, if'S'or's' is identified as SJIS. If the'U'or'u' as a UTF-8. 'N'said the wrong Chinese characters processing. This option is the default value N(NONE).
Can change text encoding approach in the future, then this option content will vary.
-d --debug
Execute the script in debug mode. Set the $DEBUG true.
-e script
Specify the script on the command line. Add the -e option, would not be drawn from the script file parameters.
If the times when you use the -e option, the system will deal with it in the following way.
Each of the following expressions of the same meaning. ruby -e "5.times do |i|" -e "puts i" -e "end" ruby -e "5.times do |i| puts i end" ruby -e "5.times do |i|; puts i; end" -Fregexp
Specify regexp to enter the field separator(field separator).
-h --help
Display command line options.
-i[extension]
The parameters specified in the contents of the file are replaced (in-place edit). The original file will be added to the extension and preserved. If no extension of words, will not back up, and only the replacement file will be retained.
An example:
% echo matz > /tmp/junk % cat /tmp/junk matz % ruby -p -i.bak -e '$_.upcase!' /tmp/junk % cat /tmp/junk MATZ % cat /tmp/junk.bak matz -I directory
The specified path loading file (additional). The specified directory is appended to the Ruby array variable ($:).
-l
Automatic processing line. First of all, will $\ to $/ value add newlines, in the print output. If using the -n logo or logo -p words, will the end of the gets read String#chop processing line!.
-n
If the use of the mark, the entire program like sed -n or awk, is
while gets ... end
Including the operation.
-p
With -n logo is similar, the output variables in each cycle of the $_value.
An example:
% echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"' MATZ -r feature
Execute the script, the first implementation of require operation on the specified database feature. Used together with the'-n'option, the'-p' option especially useful.
-s
To explain to the script name and parameters' - 'at the beginning, and the Fu value value to the same name as a global variable. Encountered with the parameters'--'first stop to explain, and remove the parameters from the ARGV.
An example:

! /usr/local/bin/ruby -s # prints "true" if invoked with `-xyz' switch. print "true\n" if $xyz -S

This option shows that, when the script name not to '/' at the beginning, to use the environment variable PATH value search script. If your machine does not support #! So, you can use the following method to simulate the operation of #!:

!/bin/sh exec ruby -S -x $0 "$@" #! ruby

Because the relationship of the first elements, the script to /bin/sh system. /bin/sh implementation of line second to start the Ruby interpreter. In the -x options under the action of the Ruby interpreter, from'#! 'to a line containing'ruby' content of all read.
根据系统的不同, $0未必包含完整路径, 因此有必要使用'-S'选项来告诉Ruby在必要时搜索脚本.
-T[level]
The implementation is not tested for purity. If level specifies a value after that, the safety level will also use this value. Level is omitted, the value 1. For CGI application, the specified is suitable for -T1. The $SAFE class will also be set.
-v --verbose
Verbose mode. Display version information is started, then the internal variable $VERBOSE is set to true. When the variable is true, the method will display verbose information at run time. If only set the'-v'option, while none of the other parameters, after the launch will be the first display version information, and then the end of operation (not wait from standard input script).
--version
Display version information of Ruby.
-w
Do not display verbose version information.
-W[level]
Ruby 1.8 features
You can specify verbose mode of 3 level, as shown below.
-W0: does not display a warning -W1: only shows important warning (default) -W2 or -W: to display all warning
$VERBOSE internal variables are set to nil,false,true.
-x[directory]
Remove the script from the message and execution. Read the script from the scope of'#! 'start, until the'ruby' contains the behavior check. Using EOF (end of file), ^D (controlD), ^Z (controlZ) or the reserved word _END_ to specify the script ends.
If the specified directory name, then moved to the specified directory in the execution of the script before.
-y --yydebug
The compiler debugging mode. Show the process of parsing script is compiled. The display will be a long process, may be useful for those who want to debug the compiler.
About the interpreter for
The script is specified on the command line to'#! 'at the beginning of the file, if'ruby' does not contain the line, will replace the OS'#! The string 'back as the command line, and then start the interpreter.
For example, SH will start to run with Ruby following shell script.

!/bin/sh -vx echo "$@"

If it contains'ruby','ruby' on the left side of the part will be ignored, the right side was regarded as the option to '-' the beginning part.
This specifies options will be appended to the command line options specified. This is mainly to embed the specified in the script options. For example, the following function equivalent script to use the command line to specify the -Ke option.

! ruby -Ke

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Paddy at December 20, 2013 - 11:41 AM