Search code examples
shellunixcomparisonshcomparison-operators

Comparision in shell script


I am doing comparision in shell script

              if [ $# -lt 10  ]
              then
              echo "PROCEED"
              else 
              echo "STOP"

I run the script as ./test.sh 1 2 3 4 5 6 7 8 9 10 11 then output is "STOP" Instead of using "-lt" if I use "<"

              if [ $# < 10  ]
              then
              echo "PROCEED"
              else 
              echo "STOP"

then output is "PROCEED".

My question is in case of shell script if I compare the no greater than 10 cause this problem. Please guide me on this


Solution

  • As seen in Advanced Bash Shell Scripting Guide - 7.3. Other Comparison Operators:

    string comparison

    <

    is less than, in ASCII alphabetical order

    if [[ "$a" < "$b" ]]

    if [ "$a" \< "$b" ]

    Note that the "<" needs to be escaped within a [ ] construct.

    So the way to do it is with -lt or, quoting again:

    integer comparison

    -lt is less than

    if [ "$a" -lt "$b" ]

    < is less than (within double parentheses)

    (("$a" < "$b"))