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

  • literal strings with whitespace ( "StackOverflow rocks!" , "Steve's Apple" )
  • variable expansions ( "$var" , "${arr[@]}" )
  • command substitutions ( "$(ls)" , "`ls`" )
  • globs where directory path or file name part includes spaces ( "/my dir/"* )
  • to protect single quotes ( "single'quote'delimited'string" )
  • Bash parameter expansion ( "${filename##*/}" )
  • Single quotes

  • command names and arguments that have whitespace in them
  • literal strings that need interpolation to be suppressed ( 'Really costs $$!' , 'just a backslash followed by at: t' )
  • to protect double quotes ( 'The "crux"' )
  • regex literals that need interpolation to be suppressed
  • use shell quoting for literals involving special characters ( $'nt' )
  • use shell quoting where we need to protect several single and double quotes ( $'{"table": "users", "where": "first_name"='Steve'}' )
  • No quotes

  • around standard numeric variables ( $$ , $? , $# etc.)
  • in arithmetic contexts like ((count++)) , "${arr[idx]}" , "${string:start:length}"
  • inside [[ ]] expression which is free from word splitting and globbing issues (this is a matter of style and opinions can vary widely)
  • where we want word splitting ( for word in $words )
  • where we want globbing ( for txtfile in *.txt; do ... )
  • where we want ~ to be interpreted as $HOME ( ~/"some dir" but not "~/some dir" )

  • See also:

  • Difference between single and double quotes in Bash
  • What are the special dollar sign shell variables?
  • 链接地址: http://www.djcxy.com/p/4122.html

    上一篇: 如何解析Bash中的命令行参数?

    下一篇: 何时在shell变量中引用引号?