Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

Shellwords.escape

(::String str) -> ::String
escape(str)

Alias of .shellescape

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.

Example
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.

Example
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.

See also .shellescape .join also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0