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

后端 未结 5 1687
孤街浪徒
孤街浪徒 2020-12-16 14:12

In shell scripting, what is the difference between these two when assigning one variable to another:

a=$b

and

a=\"$b\"
         


        
5条回答
  •  青春惊慌失措
    2020-12-16 14:48

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

提交回复
热议问题