| Module | Shellwords |
| In: |
lib/shellwords.rb
|
This module is originally a port of shellwords.pl, but modified to conform to POSIX / SUSv3 (IEEE Std 1003.1-2001).
Examples:
require 'shellwords' words = Shellwords.shellwords(line)
or
require 'shellwords' include Shellwords words = shellwords(line)
Split text into an array of tokens in the same way the UNIX Bourne shell does.
See the Shellwords module documentation for an example.
# File lib/shellwords.rb, line 28
28: def shellwords(line)
29: line = String.new(line) rescue
30: raise(ArgumentError, "Argument must be a string")
31: line.lstrip!
32: words = []
33: until line.empty?
34: field = ''
35: loop do
36: if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') then
37: snippet = $1.gsub(/\\(.)/, '\1')
38: elsif line =~ /\A"/ then
39: raise ArgumentError, "Unmatched double quote: #{line}"
40: elsif line.sub!(/\A'([^']*)'/, '') then
41: snippet = $1
42: elsif line =~ /\A'/ then
43: raise ArgumentError, "Unmatched single quote: #{line}"
44: elsif line.sub!(/\A\\(.)?/, '') then
45: snippet = $1 || '\\'
46: elsif line.sub!(/\A([^\s\\'"]+)/, '') then
47: snippet = $1
48: else
49: line.lstrip!
50: break
51: end
52: field.concat(snippet)
53: end
54: words.push(field)
55: end
56: words
57: end