Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am doing integer comparison in bash (trying to see if the user is running as root), and I found two different ways of doing it:

Double equals:

if [ $UID == 0 ]
then
fi

-eq

if [ $UID -eq 0 ]
then
fi

I understand that there's no >= or <= in bash, only -ge and -le, so why is there a == if there's a -eq?

Is there a difference in the way it compares both sides?

share|improve this question
    
Note that spaces inside brackets are required: [ $UID -eq 0 ], not [ $UID -eq 0]. –  Gilles Jul 5 '11 at 20:54
    
@Gilles- Oops, good catch. –  tjameson Jul 6 '11 at 3:54

3 Answers 3

up vote 14 down vote accepted

== is a bash-specific alias for =, which performs a string (lexical) comparison instead of a numeric comparison. (It's backwards from Perl: the word-style operators are numeric, the symbolic ones lexical.)

share|improve this answer
    
Does that mean that if both sides are integers, it converts both sides to strings and then compares them? –  tjameson Jul 5 '11 at 17:30
2  
More precisely it's the other way around: everything is a string, -eq tells bash to interpret the strings as integers (producing 0 without a warning if a string isn't numeric). –  geekosaur Jul 5 '11 at 17:34
4  
@tjameson To give an example: [ 01 -eq 1 ] but [ 01 != 1 ]. –  Gilles Jul 5 '11 at 20:54

If you want to do integer comparison you will better use (( )), where you can also use >= etc.

Example:

if (( $UID == 0 )); then
   echo "You are root"
else
   echo "You are not root"
fi
share|improve this answer

To elaborate on bollovan's answer...

There is no >= or <= comparison operator for strings. But you could use them with the ((...)) arithmetic command to compare integers.

You can also use the other string comparison operators (==, !=, <, >, but not =) to compare integers if you use them inside ((...)).

Examples

  • Both [[ 01 -eq 1 ]] and (( 01 == 1 )) do integer comparisons. Both are true.
  • Both [[ 01 == 1 ]] and [ 01 = 1 ] do string comparisons. Both are false.
  • Both (( 01 -eq 1 )) and (( 01 = 1 )) will return an error.

Note: The double bracket syntax [[...]] and the double parentheses syntax ((...)) are not supported by all shells.

share|improve this answer

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.