When to wrap quotes around a shell variable?
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?
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.
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 at: t'
) 'The "crux"'
) $'nt'
) $'{"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:
上一篇: 如何解析Bash中的命令行参数?
下一篇: 何时在shell变量中引用引号?