Method: Shellwords.shellwords

Defined in:
lib/shellwords.rb

.shellwordsObject

Splits a string into an array of tokens in the same way the UNIX Bourne shell does.

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

line must not contain NUL characters because of nature of exec system call.

Note, however, that this is not a command line parser. Shell metacharacters except for the single and double quotes and backslash are not treated as such.

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

String#shellsplit is a shortcut for this function.

argv = 'here are "two words"'.shellsplit
argv #=> ["here", "are", "two words"]


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/shellwords.rb', line 117

def shellsplit(line)
  words = []
  field = String.new
  line.scan(/\G\s*(?>([^\0\s\\\'\"]+)|'([^\0\']*)'|"((?:[^\0\"\\]|\\[^\0])*)"|(\\[^\0]?)|(\S))(\s|\z)?/m) do
    |word, sq, dq, esc, garbage, sep|
    if garbage
      b = $~.begin(0)
      line = $~[0]
      line = "..." + line if b > 0
      raise ArgumentError, "#{garbage == "\0" ? 'Nul character' : 'Unmatched quote'} at #{b}: #{line}"
    end
    # 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