MxNx
MxNx

Reputation: 1374

What is the difference between bash string with quote and without quote

Does it matter to surround string content in quote marks in Bash scripts? Consider the following two variables:

str1=hei
str2="Hi"

Which of the above ways of defining a string literal is preferred in bash and why?

Upvotes: 7

Views: 3053

Answers (1)

William Pursell
William Pursell

Reputation: 212434

It doesn't matter at all. Purely for stylistic reasons, many people will say that using the quotes is preferred. The only purpose of quotes in bash is to control word splitting and variable interpolation. (and special characters....it's probably a rather long list). Since the right hand side of your equation has no variables and no special characters, the quotes are not necessary.

Consider the following:

sp='this is a string with spaces'   #1
sp=this' is a st'rin"g wit"h\ spaces  #2 same as #1
v=$sp     #3
v="$sp"   #4  equivalent to #3
v='$sp'   #5  assign literal string $sp

2 and 3 are stylistically horrible, but completely valid. Since word splitting does not happen in a variable assignment, #3 and #4 are equivalent. The purpose of the double quotes in a string with whitespace is to prevent word-splitting (that can also be achieved with a backslash). That is, sp=this is a string would parse as an attempt to invoke a command is with the arguments a and string and the environment variable sp set to the value of this, but using quotes prevents that. The reason to use double quotes instead of single quotes is to allow variable interpolation. When a string has neither variables nor whitespace, there is no reason (other than style) to use any quotes at all.

Personally, I find the style of over-quoting to be a bit excessive. Unless a person uses quotes on an interactive prompt with command like ls "/p/a/t/h", I see no reason to use quotes when they aren't necessary. For consistency, those people advocating using quotes should always type "ls" "/p/a/t/h", and I've never known anyone to quote commands like that. OTOH, shell quoting rules can be a bit arcane (see #2 above!), and if there's any doubt, use quotes.

Upvotes: 9

Related Questions