Jordon Bedwell

I do it wrong so you can learn a new way to do it right.

Systems and Programming

On Shell Escaping in Ruby.

Its standard is too low, you can’t accidentally double escape. Here let me fix that:

module Utils
  def escape(str)
    str.gsub!(/(\\?[^A-Za-z0-9_\-.,:\/@\n])/) do
      $1.start_with?("\\") ? $1 : "\\#{$1}"
    end

    str.gsub!(/\n/,
      "'\n'"
    )

    str
  end
end
Utils.escape(Utils.escape(
  "hello\\ world"
))

# => "hello\\ world"

Like Jekyll Talk or this article? Consider donating to our hosting bill. Donate!