Thursday, April 28, 2005

Bash Comparisons

So here is the bottomline as far comparing strings and integers in bash is concerned.
You want to compare strings use

[[ $stringa < $stringb ]]

You want to compare numbers use

(( $numbera < $numberb ))

This will take you a long way without much heartburns. :)
Now lets try out a few examples to understand this thing better.

#!/bin/bash
#string.sh
EQUAL="equal"

if [ $EQUAL == "equal" ]
then
echo "I am equal"
else
echo "I am not equal"
fi

$ ./string.sh
I am equal

Now lets try something more now see if 'a' < 'b'
#!/bin/bash
#stringcmp.sh
A="a"

if [ $A < "b" ]
then
echo "a is lesser than b"
else
echo "Something went wrong"
fi


$ ./stringcmp.sh
./stringcmp.sh: line 5: b: No such file or directory
Something went wrong

Ah so we cant do that. :) . So we try '[[ ]]'

#!/bin/bash
#stringcmp.sh
A="a"

if [[ $A < "b" ]]
then
echo "a is lesser than b"
else
echo "Something went wrong"
fi

$ ./stringcmp.sh
a is lesser than b

So a more comprehensive example

#!/bin/bash
#stringcmp.sh
A="a"
C="c"
B="b"

if [[ $A < "b" ]]
then
echo "a is lesser than b"
else
echo "Something went wrong"
fi
if [[ $C < "b" ]]
then
echo "Something went wrong"
else
echo "c is not lesser than b"
fi
if [[ $B < "b" ]]
then echo "Something went wrong"
else
if [[ $B == "b" ]]
then
echo "b is equal to b"
fi
fi


$ ./stringcmp.sh
a is lesser than b
c is not lesser than b
b is equal to b

Numbers are pretty straightforward as they only work with circular parenthesis "(())".
So you cant use the examples listed above to compare numbers.

0 Comments:

Post a Comment

<< Home