Could someone tell me whether or not I should wrap quotes around variables in a shell script?
For example, is the following correct:
xdg-open $URL
[ $? -eq 2 ]
or
xdg-open "$URL"
[ "$?" -eq "2" ]
And if so, why?
Could someone tell me whether or not I should wrap quotes around variables in a shell script?
For example, is the following correct:
xdg-open $URL
[ $? -eq 2 ]
or
xdg-open "$URL"
[ "$?" -eq "2" ]
And if so, why?
Here is a three-point formula for quotes in general:
Double quotes
In contexts where we want to suppress word splitting and globbing. Also in contexts where we want the literal to be treated as a string, not a regex.
Single quotes
In string literals where we want to suppress interpolation and special treatment of backslashes. In other words, situations where using double quotes would be inappropriate.
No quotes
In contexts where we are absolutely sure that there are no word splitting or globbing issues or we do want word splitting and globbing.
Examples
Double quotes
"StackOverflow rocks!"
,"Steve's Apple"
)"$var"
,"${arr[@]}"
)"$(ls)"
,"`ls`"
)"/my dir/"*
)"single'quote'delimited'string"
)"${filename##*/}"
)Single quotes
'Really costs $$!'
,'just a backslash followed by a t: \t'
)'The "crux"'
)$'\n\t'
)$'{"table": "users", "where": "first_name"=\'Steve\'}'
)No quotes
$$
,$?
,$#
etc.)((count++))
,"${arr[idx]}"
,"${string:start:length}"
[[ ]]
expression which is free from word splitting and globbing issues (this is a matter of style and opinions can vary widely)for word in $words
)for txtfile in *.txt; do ...
)~
to be interpreted as$HOME
(~/"some dir"
but not"~/some dir"
)See also:
General rule: quote it if it can either be empty or contain spaces (or any whitespace really) or special characters (wildcards). Not quoting strings with spaces often leads to the shell breaking apart a single argument into many.
$?
doesn't need quotes since it's a numeric value. Whether$URL
needs it depends on what you allow in there and whether you still want an argument if it's empty.I tend to always quote strings just out of habit since it's safer that way.
In short, quote everything where you do not require the shell to perform token 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. Typically, it is the quoting mechanism of choice when you do not require variable interpolation.
Double quotes are suitable when variable interpolation is required. With suitable adaptations, it is also a good workaround when you need single quotes in the string. (There is no straightforward way to escape a single quote between single quotes, because there is no escape mechanism inside single quotes -- if there was, they would not quote completely verbatim.)
No quotes are suitable when you specifically require the shell to perform token splitting and/or wildcard expansion.
Token splitting;
By contrast:
(The loop only runs once, over the single, quoted string.)
(The loop only runs once, over the literal single-quoted string.)
Wildcard expansion:
By contrast:
(There is no file named literally
file*.txt
.)(There is no file named
$pattern
, either!)In more concrete terms, anything containing a filename should usually be quoted (because filenames can contain whitespace and other shell metacharacters). Anything containing a URL should usually be quoted (because many URLs contain shell metacharacters like
?
and&
). Anything containing a regex should usually be quoted (ditto ditto). Anything containing significant whitespace other than single spaces between non-whitespace characters needs to be quoted (because otherwise, the shell will munge the whitespace into, effectively, single spaces, and trim any leading or trailing whitespace).When you know that a variable can only contain a value which contains no shell metacharacters, quoting is optional. Thus, an unquoted
$?
is basically fine, because this variable can only ever contain a single number. However,"$?"
is also correct, and recommended for general consistency and correctness (though this is my personal recommendation, not a widely recognized policy).Values which are not variables basically follow the same rules, though you could then also escape any metacharacters instead of quoting them. For a common example, a URL with a
&
in it will be parsed by the shell as a background command unless the metacharacter is escaped or quoted:(Of course, this also happens if the URL is in an unquoted variable.) For a static string, single quotes make the most sense, although any form of quoting or escaping works here.
The last example also suggests another useful concept, which I like to call "seesaw quoting". If you need to mix single and double quotes, you can use them adjacent to each other. For example, the following quoted strings
can be pasted together back to back, forming a single long string after tokenization and quote removal.
This isn't awfully legible, but it's a common technique and thus good to know.
As an aside, scripts should usually not use
ls
for anything. To expand a wildcard, just ... use it.(The loop is completely superfluous in the latter example;
printf
specifically works fine with multiple arguments.stat
too. But looping over a wildcard match is a common problem, and frequently done incorrectly.)A variable containing a list of tokens to loop over or a wildcard to expand is less frequently seen, so we sometimes abbreviate to "quote everything unless you know precisely what you are doing".
For using the variables in the shell script use " " quoted variables as the quoted one means that the variable may contain spaces or special character which won't affect the execution of your shell script. Else if you are sure of not having any spaces or special character in your variable name then you may use them without " ".
Example:
echo "$url name" -- ( Can be used at all times )
echo "$url name" -- ( Cannot be used at such situations so take precaution before using it )
I generally use quoted like
"$var"
for safe, unless I am sure that$var
does not contain space.I do use
$var
as a simple way to join lines: