Quoting vs not quoting the variable on the RHS of a variable assignment Quoting vs not quoting the variable on the RHS of a variable assignment bash bash

Quoting vs not quoting the variable on the RHS of a variable assignment


I think there is no big difference here. Yes, it is advisable to enclose a variable in double quotes when that variable is being referenced. However, $x does not seem to be referenced here in your question.

y=$x does not by itself affect how whitespaces will be handled. It is only when $y is actually used that quoting matters. For example:

$ x=" a    b "$ y=$x$ echo $ya b$ echo "$y" a    b


There are no (good) reasons to double quote the RHS of a variable assignment when used as a statement on its own.

The RHS of an assignment statement is not subject to word splitting (or brace expansion), etc. so cannot need quotes to assign correctly. All other expansions (as far as I'm aware) do occur on the RHS but also occur in double quotes so the quoting serves no purpose.

That being said there are reasons not to quote the RHS. Namely how to address error "bash: !d': event not found" in Bash command substitution (specifically see my answer and rici's answer).


From section 2.9.1 of the POSIX shell syntax specification:

Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.

String-splitting and globbing (the steps which double quotes suppress) are not in this list.

Thus, the quotes are superfluous in all simple assignments (not speaking here to those implemented with arguments to declare, export or similar commands) except those where (1) the behavior of single-quoted, not double-quoted, strings are desired; or (2) whitespace or other content in the value would be otherwise parsed as syntactic rather than literal.


(Note that the decision on how to parse a command -- thus, whether it is an assignment, a simple command, a compound command, or something else -- takes place before parameter expansions; thus, var=$1 is determined to be an assignment before the value of $1 is ever considered! Were this untrue, such that data could silently become syntax, it would be far more difficult -- if not impossible -- to write secure code handling untrusted data in bash).