Flowdock
method

quote

Importance_2
v1_8_6_287 - Show latest stable - 2 notes - Class: String
quote() public

No documentation

This method has no description. You can help the Ruby community by adding new notes.

Show source
Register or log in to add new notes.
January 12, 2009
2 thanks

A word of warning

This method returns the supplied string with double quotes around it if it has a space in it, otherwise leaves it alone.

This is useful when sending paths to the shell or any similar operations. Here is a small demonstration of how it works and why it would be useful:

def cat(term)
  puts "cat #{term}"
end

def cat_q(term)
  puts "cat #{term.quote}"
end

# No difference without whitespace
cat   "hello.txt"       #=> cat hello.txt    -- OK!
cat_q "hello.txt"       #=> cat hello.txt    -- OK!

# With whitespace
cat   "hello world.txt" #=> cat hello world.txt    -- Error
                        #   trying to find "hello" or "world.txt"

cat_q "hello world.txt" #=> cat "hello world.txt"   -- OK!

Watch out if you want to do things securely, since this method does not escape quotes that are already there!

cat_q 'Peter "Smiley" McGraw.txt' #=> cat "Peter "Smiley" McGraw.txt" -- ERROR!

It is possible to insert fork bombs and other dangerous stuff by taking advantage of this, and that might take down the whole machine, steal data or delete data depending on the rights of the user executing the script.

The insecurity might also transfer into other areas in case you are not using this method for the shell, but for something else.

Please do note that most of these problems can be avoided if you just split the arguments in Ruby when doing system calls, which is easier to do most of the time.

quoted_files = file_list.collect { |f| f.quote }  
system("grep #{search.quote} #{quoted_files.join(' ')}")

system("grep", search, *file_list) # Much easier!

So, in summary: You should only use this method if you know what you’re doing! It’s neither secure nor needed in most (but not all) cases.

January 22, 2009
2 thanks

Correct way to quote for the shell

A followup for my previous comment;

I actually found a good way to handle quoting for the shell in Ruby 1.9 in case you really need to (for example to pipe the output from the examples I gave below).

require 'shellwords'

escape = lambda { |str| Shellwords.shellescape(str) }
file = %(Peter "Smiley" McGraw.txt)
puts "grep foobar #{escape[file]} > foobars"
  # => grep foobar "Peter \"Smiley\" McGraw.txt" > foobars

Do note that I have not tested this since I do not have Ruby 1.9 installed, but from what I have read, this should work properly there.

I still do not know a good way to do this in Ruby 1.8.