How to Prevent Parameter Expansion in Bash

bash

How can we prevent parameter expansion?
Does the Bash's Manual mention this somewhere? I'd appreciate
if you could help me to locate where it is mentioned there.

For example,

$ b=1
$ echo $b
1

When the bash interpreter interprets echo $b, the parameter expansion $b happens before running echo $b.
So there is no need to make b a environment variable of the shell process, in order to be passed to the subprocess for echo $b.

For comparison, consider another example from https://unix.stackexchange.com/a/261406/674

$ b=1
$ c=$(b=2; echo $b)
$ echo $c
2

In the original shell, when the bash interpreter interprets c=$(b=2; echo $b), it doesn't expand $b using the value 1.

In the subshell of the command substitution, when the bash interpreter interprets b=2; echo $b, it expands $b using the value 2.

What prevents the parameter expansion $b in the original shell, and leaves the parameter expansion $b till the subshell?

Quotes can prevent parameter expansions, e.g. "$b". But here there are no quotes around the parameter expansion. Does command substitution prevent parameter expansion in it?

Best Answer

You have mistaken, double quotes "$b" does not prevent parameter expansion, it prevents pathname expansion (aka globbing) and fields splitting.

If you want to prevent parameter expansion, you need to use quoting, like single quote '$b' or escaping \$b:

$ echo '$b'

or:

$ echo \$b

then $b is output literal.


In the example, there's nothing prevent parameter expansion.

When the shell read the input c=$(b=2; echo $b), it perform token recognition, saw that $( is token for command substitution. So it treats the rest of string between $( and ) to be interpreted in subshell created by command substitution, not the current shell.

Related Question