End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
class method
Shellwords.shellsplit
shellsplit(line)
lib/shellwords.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.1.3/lib/shellwords.rb, line 88
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 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
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"]
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"]