stringgocommand-line-arguments

Backslashes are removed unless quoted in command line flags


I'm using the flag package to interpret flags entered at the command line.

I created a variable using

ptrString := flag.String("string", "", "A test string")
flat.Parse()

Then when I want to print it,

fmt.Println("You entered " + *ptrString)

If I enter something like -string=hello! as a command line argument, it prints "hello!"

If I enter something like -string=hello\Bob as a command line argument, it prints "helloBob"

Is there a recommended way to convert or interpret the flag argument to a string that doesn't remove the backslash? (This is being tested on Linux and OS X, if the shell is interfering...)


Solution

  • Characters that have special meaning in the shell need to be quoted or escaped. You can find complete list in the shell's man pages (under "Quoting" in man 1 bash).

    In this case, you can either quote or escape the baskslash

    -string=hello\\Bob
    // or
    -string='hello\Bob'