0

Are the following two boolean expressions the same?

if [ -n $1 ] ; then

if [ -n "$1" ] ; then

If not - When should you put a variable in quotes?

0

Here is an example that should demonstrate the difference

~$ t="alfa beta"
~$ if [ -n $t ] ; then echo OK ; fi 
 bash: [: alfa: binary operator expected
~$ if [ -n "$t" ] ; then echo OK ; fi 
 OK
~$ ls blah*
blah1 blah2 blah3
~$ t="blah*"
~$ if [ -n "$t" ] ; then echo OK ; fi 
 OK
~$ if [ -n $t ] ; then echo OK ; fi
bash: [: too many arguments

In other words, with quotes, the $t is expanded only once and put in quotes as a single argument to test ([ is just an alias to test). Without quotes, it is substituted by the contents of $t and then expanded again.

0

In the test conditions, which is the same as [, you should always use double quotes, otherwise the test command might miss an argument if the variable is empty or undefined, or have too many arguments if the variable contains whitespace. In bash, though, it is safer to use the builtin [[ for conditions that does not need the quotes.

Not the answer you're looking for? Browse other questions tagged or ask your own question.