1

I do not understand what is happening here, based on Convert string into integer in bash script - "Leading Zero" number error, I am able to convert the string into integer. I can even do addition. However, when I compare the numbers it gives me the wrong comparison. Refer to example below

Here's an example

array=(02 08 10 11 23 52)

for i in 0 1 2 3 4 5
    do
        if [[ ${array[i]#0} > 15 ]]
        then
            echo "${array[i]#0} is greater than 15"
        else
            echo "${array[i]#0} is less than 15"
        fi
done

Output

2 is greater than 15
8 is greater than 15
10 is less than 15
11 is less than 15
23 is greater than 15
52 is greater than 15
Shira
  • 35
  • 4
  • 3
    I suggest to replace `>` with `-gt` for arithmetic tests. – Cyrus Oct 11 '21 at 23:44
  • 1
    Does this answer your question? [How can I compare numbers in Bash?](https://stackoverflow.com/questions/18668556/how-can-i-compare-numbers-in-bash) - the leading `0` isn't the problem here, since your values don't change in octal; it's all about the position of "15" versus "2" in a dictionary-style string ordering. – Jeff Bowman Oct 11 '21 at 23:44
  • @dawg yep that helped a lot, I never knew there was so much difference. Thanks! – Shira Oct 12 '21 at 00:16

1 Answers1

2

Either change [[ ]] to (( )) to use > or change the operator to -gt to do integer comparisons inside of [[ ]]

First:

#!/bin/bash

array=(02 08 10 11 23 52)

for i in 0 1 2 3 4 5
do
    if (( ${array[i]#0} > 15 ))
    then
        echo "${array[i]#0} is greater than 15"
    else
        echo "${array[i]#0} is less than 15"
    fi
done

Second:

#!/bin/bash

array=(02 08 10 11 23 52)

for i in 0 1 2 3 4 5
do
    if [[ ${array[i]#0} -gt 15 ]]
    then
        echo "${array[i]#0} is greater than 15"
    else
        echo "${array[i]#0} is less than 15"
    fi
done

If you use < > == inside of [ ] or [[ ]] is a string comparison operator. The string "02" is in fact less than the string "15":

% [[ 02 > 15 ]]; echo $?
1                        # '1' means false and '0' means true

BUT you are stripping the leading "0" with #0:

% s="02"
% echo ${s#0}
2

So now you are comparing the STRING "2" to the STRING "15":

% [[ 2 > 15 ]]; echo $?
0 
% [[ ${s#0} > 15 ]]; echo $?
0

Which give the surprising result you are seeing...

See this answer for an expanded set of examples.

dawg
  • 98,345
  • 23
  • 131
  • 206