Ruby: How to insert three backslashes into a string?

402 Views Asked by At

I want to use backticks in ruby for a programm call. The parameter is a String variable containing one or more backticks, i.e. "&E?@@A`?". The following command yields a new label as its return value:

echo "&E?@@A\`?" | nauty-labelg 2>/dev/null

From a ruby program I can call it as follows and get the correct result:

new_label = `echo "&E?@@A\\\`?" | nauty-labelg 2>/dev/null`

I want to achieve the same using a variable for the label. So I have to insert three slashes into my variable label = "&E?@@A`?" in order to escape the backtick. The following seems to work, though it is not very elegant:

escaped_label = label.gsub(/`/, '\\\`').gsub(/`/, '\\\`').gsub(/`/, '\\\`')

But the new variable cannot be used in the program call:

new_label = `echo "#{escaped_label}" | nauty-labelg 2>/dev/null`

In this case I do not get an answer from nauty-labelg.

1

There are 1 best solutions below

2
3limin4t0r On

So I have to insert three slashes into my variable label = "&E?@@A`?" in order to escape the backtick.

No, you only need to add one backslash for the output. To escape the ` special bash character. The other other two are only for representation proposes, otherwise it isn't valid Ruby code.

new_label = `echo "&E?@@A\\\`?" | nauty-labelg 2>/dev/null`

The first backslash will escape the second one (outputting one single backslash). The third backslash escapes the ` character (outputting one single `).

You should only add backslashes before characters that have a special meaning within double quoted bash context. These special characters are: $, `, \ and \n. Those can be escaped with the following code:

def escape_bash_string(string)
  string.gsub(/([$`"\\\n])/, '\\\\\1')
end

For label = "&E?@@A`?" only the ` should be escaped.

escaped_string = escape_bash_string("&E?@@A\`?")
puts escaped_string
# &E?@@A\`?