Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question
    
While this is not strictly off-topic, it could get more attention at Stack Overflow, or possibly Unix & Linux. –  hexafraction Aug 30 '12 at 17:14
    
Thanks - I posted this question on stackoverflow stackoverflow.com/questions/12202778/… and would like to request that this question gets deleted from askubuntu –  user784637 Aug 30 '12 at 18:07
add comment

closed as too localized by Marco Ceppi Aug 30 '12 at 19:51

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

up vote 0 down vote accepted

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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