Given this code, I can't figure out how to escape the backtick.
var (
MY_STRING = "something`something"
)
cmd := fmt.Sprintf("MY_ENV=%q;", MY_STRING)
out, err := exec.Command("bash", "-c", cmd).CombinedOutput()
// results in MY_ENV="something`something" ie unfinished input
I've tried the below but it results in "unknown escape sequence". It does work in the shell obviously. I've also tried to combine strings and raw string literals but with no success. How can I escape the backtick please?
var (
MY_STRING = "something\`something"
)
Use '
to escape `
in Bourne shells. And no need to quote the string.
MY_STRING := "something'`'something"
cmd := fmt.Sprintf("MY_ENV=%s;", MY_STRING)
out, err := exec.Command("bash", "-c", cmd).CombinedOutput()
The backtick doesn’t need escaping for Go to leave it in the string (ref).
However, bash will treat backticks outside of a string as subshell syntax. The easiest way to escape a backtick in bash is to include it in a single-quoted string:
var MY_STRING = "'something`something'"
But since you’re using %q
in your format string, this won’t behave as expected.
Instead, you can use the solution posted on this question. Bash requires double escaping the backtick (\\\`
) inside double quotes. There’s a full explanation for why this is necessary in that linked question. Since Go also uses \
as an escape character, you’ll need to double up each one:
var MY_STRING = "something\\\\\\`something"