Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

a=$b

and

a="$b"

and when should I use one over the other?

like image 517
John Avatar asked Oct 18 '10 11:10

John


People also ask

Do variables need quotation marks?

Storing text in variables Double quotes are required if there is going to be an apostrophe in the string. Try storing a string within a variable without quotes, see what happens? Numbers do not require quotation marks, whereas they are mandatory for storing strings.

Why is it a good practice to put arguments in quotes when assigning them to variables?

In short, quote everything where you do not require the shell to perform word splitting and wildcard expansion. Single quotes protect the text between them verbatim. It is the proper tool when you need to ensure that the shell does not touch the string at all.

How do you use variables in a quote?

[1] Keeping $ as a special character within double quotes permits referencing a quoted variable ("$variable"), that is, replacing the variable with its value (see Example 4-1, above). Use double quotes to prevent word splitting.

Which variable is enclosed in single quotes?

Strings are identified by enclosing them in quotes: "This is a string of characters." Character strings are treated as single blocks of text that can be put together (concatenated) to create a longer character string from the separate strings, or they can be taken apart to extract substrings composed of portions of the ...


1 Answers

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 $y
a b
$ echo "$y"
 a    b
like image 139
n.r. Avatar answered Oct 05 '22 10:10

n.r.