1

I'm trying to backslash-escape a filename that has backticks in it, to pass to some shell commands. I am seeing some weird behavior when trying to use gsub for this.

Some examples in IRB:

irb(main):001:0> 'weird`things'.gsub('`', '\`')
=> "weirdweirdthings"
irb(main):002:0> 'weird`things'.gsub('`', '\\`')
=> "weirdweirdthings"
irb(main):003:0> 'weird`things'.gsub('`', '\\\`')
=> "weird\\`things"    # this is what I want
irb(main):004:0> 'weird`things'.gsub('`', '\\\\`')
=> "weird\\`things"
irb(main):005:0> 'weird`things'.gsub('`', '\\\\\`')
=> "weird\\weirdthings"

What is going on here? Does this have something to do with the $` global variable?

mikrostew
  • 65
  • 8
  • 2
    Also you might want to check out `Shellwords.escape`: http://stackoverflow.com/questions/6921599/ruby-escape-argv-argument-or-string-as-argument-to-shell-command/6922339 – Casper Aug 07 '15 at 21:15
  • Thanks @Casper, that's just what I needed! – mikrostew Aug 07 '15 at 21:22
  • Or even better, don't build command lines as strings, use the multi-argument version of [`system`](http://ruby-doc.org/core-2.2.2/Kernel.html#method-i-system) or [`Open3`](http://ruby-doc.org/stdlib-2.2.2/libdoc/open3/rdoc/index.html) and avoid the shell entirely. – mu is too short Aug 07 '15 at 22:01

0 Answers0