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?
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.
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.
[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.
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 ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With