Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

when comparing two integers in bash, do we have to put double quotes ? In the official document http://tldp.org/LDP/abs/html/comparison-ops.html I can read that double quotes should appear every time... But what is the differences in the following examples:

[ "$VAR" -eq "1" ]
[ $VAR -eq "1" ]
[ "$VAR" -eq 1 ]
[ $VAR -eq 1 ]

As I am curious, a took a look at Ubuntu init scripts in /etc/init.d and there are many usage of arithmetic comparison in it, at least [ "$VAR" -eq "1" ] and [ $VAR -eq 1 ] are used... but it seems no one really "knows" what is the official way to do it.

Thanks !

share|improve this question

2 Answers 2

up vote 3 down vote accepted

You need to quote $VAR if it could possibly be empty/unset (so you should probably always quote it).

If you don't quote it and it's empty, the statement results in:

[ -eq 1 ]

which is a syntax error. Quoting the 1 doesn't gain anything though.

(Also look at bash conditional expressions (things with [[ ... ]]), a more "modern" version of the test command that has less quirks.)

share|improve this answer
    
As far as I know [ invokes the test-command, while [[ is a Bash-builtin...so it might not be an option. –  Bobby Nov 29 '12 at 10:44
    
I know, that's why it's added as a note (and that's also why it doesn't have the same quirks). Question is tagged bash though, so I believe it's relevant. –  Mat Nov 29 '12 at 10:45
    
Thanks ! It answers my question :) –  Martin Nov 29 '12 at 11:14
1  
[ is a bash builtin -- see type \[ –  glenn jackman Nov 29 '12 at 11:56
    
Quoting an undefined variable still throws an error (integer expression expected) since its trying to compare an empty string with an integer... –  Jason Zhu May 19 at 15:24

If you want to arithmetic comparison, use the arithmetic conditional construct (documented here):

(( VAR == 1 ))
share|improve this answer
    
It's true that I learned (about ten years ago) to handle arithmetics comparison with "[" bash bultin , so it's not easy to let it go ^^ –  Martin Dec 4 '12 at 9:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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