class method
Shellwords.shellsplit
(::String line) -> ::Array[::String]
shellsplit(line)
lib/shellwords.rb
View on GitHub ↗
# File tmp/rubies/ruby-4.0.0/lib/shellwords.rb, line 90
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
Splits a string into an array of tokens in the same way the UNIX Bourne shell does.
Example
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.
Example
argv = Shellwords.split('ruby my_prog.rb | less') argv #=> ["ruby", "my_prog.rb", "|", "less"]
String#shellsplit is a shortcut for this function.
Example
argv = 'here are "two words"'.shellsplit argv #=> ["here", "are", "two words"]