Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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.

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… and would like to request that this question gets deleted from askubuntu – user784637 Aug 30 '12 at 18:07
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 
~$ ls blah*
blah1 blah2 blah3
~$ t="blah*"
~$ if [ -n "$t" ] ; then echo OK ; fi 
~$ 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

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

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