Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shellwords.shellescape implementation for Ruby 1.8

While the build of 1.8.7 I have seems to have a backported version of Shellwords::shellescape, I know that method is a 1.9 feature and definitely isn't supported in earlier versions of 1.8. Does anyone know where I can find, either in Gem form or just as a snippet, a robust standalone implementation of Bourne-shell command escaping for Ruby?

like image 942
Avdi Avatar asked Aug 20 '09 14:08

Avdi


2 Answers

You might as well just copy what you want from shellwords.rb in the trunk of Ruby's subversion repository (which is GPLv2'd):

  def shellescape(str)
    # An empty argument will be skipped, so return empty quotes.
    return "''" if str.empty?

    str = str.dup

    # Process as a single byte sequence because not all shell
    # implementations are multibyte aware.
    str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1")

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

    return str
  end
like image 183
Bkkbrad Avatar answered Nov 16 '22 09:11

Bkkbrad


I wound up going with the Escape gem, which has the additional feature of using quotes by default, and only backslash-escaping when necessary.

like image 21
Avdi Avatar answered Nov 16 '22 09:11

Avdi