非常教程

Ruby 2.4参考手册

Shell

Shellwords

操作像UNIX Bourne shell这样的字符串

此模块根据UNIX Bourne shell的单词分析规则处理字符串。

shellwords()函数最初是shellwords.pl的一个端口,但被修改为符合IEEE Std 1003.1-2008,2016年版1的Shell&Utilities卷。

用法

您可以使用Shellwords将字符串解析为Bourne shell友好的数组。

require 'shellwords'

argv = Shellwords.split('three blind "mice"')
argv #=> ["three", "blind", "mice"]

一旦你需要Shellwords,你可以使用拆分别名String#shellsplit。

argv = "see how they run".shellsplit
argv #=> ["see", "how", "they", "run"]

注意不要留下不匹配的引用。

argv = "they all ran after the farmer's wife".shellsplit
     #=> ArgumentError: Unmatched double quote: ...

在这种情况下,您可能想要使用:: escape或其别名String#shellescape。

此方法会转义字符串,以供您安全地使用Bourne shell。

argv = Shellwords.escape("special's.txt")
argv #=> "special\\'s.txt"
system("cat " + argv)

Shellwords还附带Array,Array#shelljoin的核心扩展。

argv = %w{ls -lta lib}
system(argv.shelljoin)

您可以使用此方法从由空格分隔的令牌数组中创建转义字符串。在这个例子中,我们使用了Array.new的文字快捷键。

公共类方法

escape(str)

别名为:shellescape

join(array)

别名为:shelljoin

shellescape(str) Show source

转义字符串以便它可以安全地在Bourne shell命令行中使用。 str可以是一个响应to_s的非字符串对象。

请注意,结果字符串应该不加引号使用,不适用于双引号或单引号。

argv = Shellwords.escape("It's better to give than to receive")
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

String#shellescape是此函数的简写。

argv = "It's better to give than to receive".shellescape
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

# Search files in lib for method definitions
pattern = "^[ \t]*def "
open("| grep -Ern #{pattern.shellescape} lib") { |grep|
  grep.each_line { |line|
    file, lineno, matched_line = line.split(':', 3)
    # ...
  }
}

调用者有责任将字符串编码为使用此字符串的shell环境的正确编码。

多字节字符被视为多字节字符,而不是字节。

如果str长度为零,则返回一个空的带引号的字符串。

# File lib/shellwords.rb, line 138
def shellescape(str)
  str = str.to_s

  # An empty argument will be skipped, so return empty quotes.
  return "''".dup if str.empty?

  str = str.dup

  # Treat multibyte characters as is.  It is the caller's responsibility
  # to encode the string in the right encoding for the shell
  # environment.
  str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\\\1")

  # A LF cannot be escaped with a backslash because a backslash + LF
  # combo is regarded as a line continuation and simply ignored.
  str.gsub!(/\n/, "'\n'")

  return str
end

另外别名为:escape

shelljoin(array) Show source

从参数列表构建命令行字符串,array

所有元素都加入到一个字符串中,并用空格分隔字段,其中每个元素都为Bourne shell转义并使用to_s进行字符串化。

ary = ["There's", "a", "time", "and", "place", "for", "everything"]
argv = Shellwords.join(ary)
argv #=> "There\\'s a time and place for everything"

Array#shelljoin是此函数的快捷方式。

ary = ["Don't", "rock", "the", "boat"]
argv = ary.shelljoin
argv #=> "Don\\'t rock the boat"

您还可以在Array#join中允许的元素中混合非字符串对象。

output = %x`#{['ps', '-p', $$].shelljoin}`
# File lib/shellwords.rb, line 184
def shelljoin(array)
  array.map { |arg| shellescape(arg) }.join(' ')
end

还有别名:连接

shellsplit(line) Show source

按照与UNIX Bourne shell相同的方式将字符串拆分为一组令牌。

argv = Shellwords.split('here are "two words"')
argv #=> ["here", "are", "two words"]

但请注意,这不是命令行解析器。除单引号和双引号以及反斜杠以外的Shell元字符不会被视为这样。

argv = Shellwords.split('ruby my_prog.rb | less')
argv #=> ["ruby", "my_prog.rb", "|", "less"]

String#shellsplit是此函数的快捷方式。

argv = 'here are "two words"'.shellsplit
argv #=> ["here", "are", "two words"]
# File lib/shellwords.rb, line 78
def shellsplit(line)
  words = []
  field = String.new
  line.scan(/\G\s*(?>([^\s\\\"]+)|'([^\]*)'|"((?:[^\"\]|\.)*)"|(\.?)|(\S))(\s|\z)?/m) do
    |word, sq, dq, esc, garbage, sep|
    raise ArgumentError, "Unmatched double quote: #{line.inspect}" if garbage
    # 2.2.3 Double-Quotes:
    #
    #   The <backslash> shall retain its special meaning as an
    #   escape character only when followed by one of the following
    #   characters when considered special:
    #
    #   $ ` " \ <newline>
    field << (word || sq || (dq && dq.gsub(/\([$`"\\n])/, '\1')) || esc.gsub(/\(.)/, '\1'))
    if sep
      words << field
      field = String.new
    end
  end
  words
end

还有别名:shellwords,split

shellwords(line)

别名为:shellsplit

split(line)

别名为:shellsplit

私有实例方法

shellescape(str) Show source

转义字符串以便它可以安全地在Bourne shell命令行中使用。 str可以是一个响应to_s的非字符串对象。

请注意,结果字符串应该不加引号使用,不适用于双引号或单引号。

argv = Shellwords.escape("It's better to give than to receive")
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

String#shellescape是此函数的简写。

argv = "It's better to give than to receive".shellescape
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

# Search files in lib for method definitions
pattern = "^[ \t]*def "
open("| grep -Ern #{pattern.shellescape} lib") { |grep|
  grep.each_line { |line|
    file, lineno, matched_line = line.split(':', 3)
    # ...
  }
}

调用者有责任将字符串编码为使用此字符串的shell环境的正确编码。

多字节字符被视为多字节字符,而不是字节。

如果str长度为零,则返回一个空的带引号的字符串。

# File lib/shellwords.rb, line 138
def shellescape(str)
  str = str.to_s

  # An empty argument will be skipped, so return empty quotes.
  return "''".dup if str.empty?

  str = str.dup

  # Treat multibyte characters as is.  It is the caller's responsibility
  # to encode the string in the right encoding for the shell
  # environment.
  str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\\\1")

  # A LF cannot be escaped with a backslash because a backslash + LF
  # combo is regarded as a line continuation and simply ignored.
  str.gsub!(/\n/, "'\n'")

  return str
end

另外别名为:escape

shelljoin(array) Show source

从参数列表构建命令行字符串,array

所有元素都加入到一个字符串中,并用空格分隔字段,其中每个元素都为Bourne shell转义并使用to_s进行字符串化。

ary = ["There's", "a", "time", "and", "place", "for", "everything"]
argv = Shellwords.join(ary)
argv #=> "There\\'s a time and place for everything"

Array#shelljoin是此函数的快捷方式。

ary = ["Don't", "rock", "the", "boat"]
argv = ary.shelljoin
argv #=> "Don\\'t rock the boat"

您还可以在Array#join中允许的元素中混合非字符串对象。

output = %x`#{['ps', '-p', $$].shelljoin}`
# File lib/shellwords.rb, line 184
def shelljoin(array)
  array.map { |arg| shellescape(arg) }.join(' ')
end

还有别名:join

shellsplit(line) Show source

按照与UNIX Bourne shell相同的方式将字符串拆分为一组令牌。

argv = Shellwords.split('here are "two words"')
argv #=> ["here", "are", "two words"]

但请注意,这不是命令行解析器。除单引号和双引号以及反斜杠以外的Shell元字符不会被视为这样。

argv = Shellwords.split('ruby my_prog.rb | less')
argv #=> ["ruby", "my_prog.rb", "|", "less"]

String#shellsplit是此函数的快捷方式。

argv = 'here are "two words"'.shellsplit
argv #=> ["here", "are", "two words"]
# File lib/shellwords.rb, line 78
def shellsplit(line)
  words = []
  field = String.new
  line.scan(/\G\s*(?>([^\s\\\"]+)|'([^\]*)'|"((?:[^\"\]|\.)*)"|(\.?)|(\S))(\s|\z)?/m) do
    |word, sq, dq, esc, garbage, sep|
    raise ArgumentError, "Unmatched double quote: #{line.inspect}" if garbage
    # 2.2.3 Double-Quotes:
    #
    #   The <backslash> shall retain its special meaning as an
    #   escape character only when followed by one of the following
    #   characters when considered special:
    #
    #   $ ` " \ <newline>
    field << (word || sq || (dq && dq.gsub(/\([$`"\\n])/, '\1')) || esc.gsub(/\(.)/, '\1'))
    if sep
      words << field
      field = String.new
    end
  end
  words
end

还有别名:shellwords,split

shellwords(line)

别名为:shellsplit

Shell相关

Ruby 2.4

Ruby 是一种面向对象、命令式、函数式、动态的通用编程语言,是世界上最优美而巧妙的语言。

主页 https://www.ruby-lang.org/
源码 https://github.com/ruby/ruby
版本 2.4
发布版本 2.4.1

Ruby 2.4目录

1.缩略 | Abbrev
2.ARGF
3.数组 | Array
4.Base64
5.基本对象 | BasicObject
6.基准测试 | Benchmark
7.BigDecimal
8.绑定 | Binding
9.CGI
10.类 | Class
11.比较 | Comparable
12.负责 | Complex
13.计算续体 | Continuation
14.覆盖 | Coverage
15.CSV
16.日期 | Date
17.日期时间 | DateTime
18.DBM
19.代理 | Delegator
20.摘要 | Digest
21.Dir
22.DRb
23.编码 | Encoding
24.枚举 | Enumerable
25.枚举 | Enumerator
26.ENV
27.ERB
28.错误 | Errors
29.Etc
30.期望值 | Exception
31.错误类 | FalseClass
32.Fiber
33.Fiddle
34.文件 | File
35.文件实用程序 | FileUtils
36.查找 | Find
37.浮点 | Float
38.Forwardable
39.GC
40.GDBM
41.GetoptLong
42.Hash
43.Integer
44.IO
45.IPAddr
46.JSON
47.Kernel
48.语言 | 3Language
49.记录 | Logger
50.编排 | Marshal
51.MatchData
52.数学 | Math
53.矩阵 | Matrix
54.方法 | Method
55.模型 | Module
56.监控 | Monitor
57. 互斥 | Mutex
58.Net
59.Net::FTP
60.Net::HTTP
61.Net::IMAP
62.Net::SMTP
63.NilClass
64.数字 | Numeric
65.对象 | Object
66.ObjectSpace
67.Observable
68.Open3
69.OpenSSL
70.OpenStruct
71.OpenURI
72.OptionParser
73.路径名 | Pathname
74.完整输出 | PrettyPrint
75.Prime
76.Proc
77.过程 | Process
78.PStore
79.PTY
80.队列 | Queue
81.随机 | Random
82.范围 | Range
83.合理的 | Rational
84.Readline
85.Regexp
86.Resolv
87.Ripper
88.RubyVM
89.Scanf
90.SDBM
91.SecureRandom
92.Set
93.Shell
94.信号 | Signal
95.Singleton
96.套接字 | Socket
97.字符串 | String
98.StringIO
99.StringScanner
100.结构 | Struct