Using the [ (yes, this is a command) command, you should almost always use quotation marks. Exceptions are so rare that I can't even get into them. For instance,
set -- 'x -a -zb' if [ -n $1 ]; then echo foo; fi
Bash also has a keyword [[ (yes, this keyword), which is smart enough to know about extensions and avoid the traps of not citing. (But still, itβs generally safe to quote inside expressions [[ .)
Since the command [ corresponds to POSIX, and [[ is the basis, you decide when to use it.
As for your second example, if you are comparing something with a number, using == is a bagism. If you are writing for bash, use an arithmetic expression like
if (( $? == 0 )); then β¦
But if you are trying to run POSIX, write
if [ "$?" = 0 ]; then β¦
Often direct comparisons with $? are a red flag because a teamβs success / failure comparison matches exactly if :
if somecommand; then β¦
better than
somecommand if (( $? == 0 )); then β¦
But if you need to use it, $? is something like an exception, because it is guaranteed that there will only ever be a single-byte unsigned integer, so itβs quite safe to use unquoted data, although this will not damage the quote.
$ false; if [ $? = 0 ]; then echo t; else echo f; fi f $ true; if [ $? = 0 ]; then echo t; else echo f; fi t $ false; if [ "$?" = 0 ]; then echo t; else echo f; fi f $ true; if [ "$?" = 0 ]; then echo t; else echo f; fi t $ false; if [ $? == 0 ]; then echo t; else echo f; fi f $ true; if [ $? == 0 ]; then echo t; else echo f; fi t $ false; if [ "$?" == 0 ]; then echo t; else echo f; fi f $ true; if [ "$?" == 0 ]; then echo t; else echo f; fi t