Method: Shellwords.shellescape

Defined in:
lib/shellwords.rb

.shellescape(str) ⇒ Object Also known as: escape

Escapes a string so that it can be safely used in a Bourne shell command line. str can be a non-string object that responds to to_s.

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

Note that a resulted string should be used unquoted and is not intended for use in double quotes nor in single quotes.

argv = Shellwords.escape("It's better to give than to receive")
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

String#shellescape is a shorthand for this function.

argv = "It's better to give than to receive".shellescape
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

# Search files in lib for method definitions
pattern = "^[ \t]*def "
open("| grep -Ern -e #{pattern.shellescape} lib") { |grep|
  grep.each_line { |line|
    file, lineno, matched_line = line.split(':', 3)
    # ...
  }
}

It is the caller’s responsibility to encode the string in the right encoding for the shell environment where this string is used.

Multibyte characters are treated as multibyte characters, not as bytes.

Returns an empty quoted String if str has a length of zero.

Raises:

  • (ArgumentError)

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/shellwords.rb', line 158

def shellescape(str)
  str = str.to_s

  # An empty argument will be skipped, so return empty quotes.
  return "''".dup if str.empty?

  # Shellwords cannot contain NUL characters.
  raise ArgumentError, "NUL character" if str.index("\0")

  str = str.dup

  # Treat multibyte characters as is.  It is the caller's responsibility
  # to encode the string in the right encoding for the shell
  # environment.
  str.gsub!(/[^A-Za-z0-9_\-.,:+\/@\n]/, "\\\\\\&")

  # A LF cannot be escaped with a backslash because a backslash + LF
  # combo is regarded as a line continuation and simply ignored.
  str.gsub!(/\n/, "'\n'")

  return str
end