LuMa LuMa - 1 year ago 82
Linux Question

Can I prevent echo from expanding env vars?

I have an automatic setup script that is executed when a new user is created. It runs this line of code to set up the golang environment:

echo "export PATH="$PATH:$GOPATH/bin"" >> ~/.profile

But this will expand all environment variables before writing into the file. Is there a way to write
export PATH="$PATH:$GOPATH/bin"
into a file from the command line without expanding the environment variables?

Answer Source


echo 'export PATH="$PATH:$GOPATH/bin"' >> ~/.profile

Single-quoted strings in POSIX-like shells (such as bash) treat their content as literals, which is what you want here.

The only reason to use a double-quoted string here would be to selectively expand variable references up front - which doesn't apply in your case.

That said, here's an example:

$ echo "Honey, I'm \"$USER\" and I'm \$HOME."
Honey, I'm "jdoe" and I'm $HOME.

Backslash-escaping is used to escape embedded " and $ instances that should be treated as literals.

As for what you tried:

"export PATH="$PATH:$GOPATH/bin""

is actually a string concatentation, composed of 3 separate strings:

  • "export PATH=", which, as a double-quoted string that happens not to contains $-prefixed interpolation elements, expands to literal export PATH=
  • $PATH:$GOPATH/bin, which, as an unquoted string, is subject to additional shell expansions, which not only involves expanding variables $PATH and $GOPATH to their respective values, but also applies word-splitting and pathname expansion (globbing).
  • "", which amounts to the empty string and is effectively ignored.

Note how POSIX-like shells allow you to compose larger strings (concatenate strings) by placing strings - unquoted or single-quoted or double-quoted - directly next to one another.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download