Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/shellwords.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ module Shellwords
def shellsplit(line)
words = []
field = String.new
field_started = false
line.scan(/\G\s*(?>([^\0\s\\\'\"]+)|'([^\0\']*)'|"((?:[^\0\"\\]|\\[^\0])*)"|(\\[^\0]?)|(\S))(\s|\z)?/m) do
|word, sq, dq, esc, garbage, sep|
if garbage
Expand All @@ -105,10 +106,16 @@ def shellsplit(line)
# characters when considered special:
#
# $ ` " \ <newline>
field << (word || sq || (dq && dq.gsub(/\\([$`"\\\n])/, '\\1')) || esc.gsub(/\\(.)/, '\\1'))
if sep
# A backslash-newline outside quotes is a line continuation and is
# removed entirely.
unless esc == "\\\n"
field << (word || sq || (dq && dq.gsub(/\\([$`"\\\n])/) { $1 == "\n" ? "" : $1 }) || esc.gsub(/\\(.)/, '\\1'))
field_started = true
end
if sep && field_started
words << field
field = String.new
field_started = false
end
end
words
Expand Down
11 changes: 11 additions & 0 deletions test/test_shellwords.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ def test_shellwords
shellwords(cmd2))
end

def test_backslash_newline
assert_equal(["foobar"], shellwords("foo\\\nbar"))
assert_equal(["foo", "bar"], shellwords("foo \\\n bar"))
assert_equal(["foo", "bar"], shellwords("foo\\\n bar"))
assert_equal(["foo"], shellwords("foo \\\n"))
assert_equal([], shellwords("\\\n"))
assert_equal(["foobar"], shellwords("\"foo\\\nbar\""))
assert_equal(["foo\\\nbar"], shellwords("'foo\\\nbar'"))
assert_equal(["foo\nbar"], shellwords("foo'\n'bar"))
end

def test_unmatched_double_quote
bad_cmd = 'one two "three'
assert_raise ArgumentError do
Expand Down
Loading