When to wrap quotes around a shell variable?
bash, linux, quotes, shell, unix
Solution
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.
Problem
Should or should I not 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?
Related problems
- Which characters need to be escaped when using Bash?
- I just assigned a variable, but echo $variable shows something else
- What is the cleanest way to ssh and run multiple commands in Bash?
- What are the special dollar sign shell variables?
- Difference between single and double quotes in Bash
- Printing asterisk ("*") in bash shell