Escape backtick in Go (string used in exec.Command)

Issue

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"
)

Solution

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()

Answered By – ᅙᄉᅙ

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.