Friday, November 21, 2008

String and Number Comparison In Shell Scripting

In shell, you will need to compare either string or number. There is a subtle different between the two and here I will try to explain that in details.

For string comparison, you will use these operators

  • = (string equal)
  • != (sting not equal)

For number comparison, you will use these operators

  • -eq (number eqaul)
  • -ne (number not equal)
  • -gt (number greater than)
  • -ge (number greater than or equal)
  • -lt (number less than)
  • -le (number less than or equal)

So what's the different between the two equals. Let's find out from the these two cases

  1. 6 = 6 vs 6 -eq 6
  2. 06 = 6 vs 06 -eq 6
Case 1: they are both equated to true because string '6' and string '6' are the same, and number 6 and number 6 are equal
Case 2: string '06' and '6' are different string, so it will equate to false. However, for number comparison 06 is 6 and therefore number 6 equals to 6

$ if [ 6 = 6 ]; then echo equal; else echo not equal; fi
equal

$ if [ 6 -eq 6 ]; then echo equal; else echo not equal; fi
equal

$ if [ 06 = 6 ]; then echo equal; else echo not equal; fi
not equal

$ if [ 06 -eq 6 ]; then echo equal; else echo not equal; fi
equal

In other scripting languages, like Tcl, anything number with a '0' in front is considered octal (base 8). So '09' is invalid in Tcl. Whereas in shell, they simply treat every number as decimal.

$ if [ 09 -eq 9 ]; then
      echo equal
  fi
equal

$ tclsh
% if { 06 == 6 } { puts equal }
equal
% if { 09 == 9 } { puts equal }
expected integer but got "09" (looks like invalid octal number)
%

Labels:

0 Comments:

Post a Comment

<< Home