user3018947
user3018947

Reputation: 51

Bash comparing array value to find max

I'm trying to find the max in an array of integers in bash. I'm pretty new to bash. Here is what I have so far...

    max="${array[0]}"
    for ((i=0;i<${#array[@]};i++))
    do  
        if [ ${array[$i]} > $max ]
        then
            max="${array[$i]}"

        fi
    done

where the array is around 500 positive integers ex. 24 27 13 34 2 104 645 411 1042 38 5 24 120 236 2 33 6. Currently it is always returning the last integer in my array. Seems like it should be an easy fix, but I'm not sure what I'm missing. Thanks for any help.

Upvotes: 2

Views: 1435

Answers (2)

chepner
chepner

Reputation: 531055

Rather than iterating over the index, iterate over the items themselves. More specific to your actual problem, make sure you are doing an arithmetic comparison, not a string comparison.

max="${array[0]}"
for i in "${array[@]}"; do
    (( i > $max )) && max=$i
done

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246774

This test [ ${array[$i]} > $max ] is performing a lexical comparison, so 99 is greater than 100

You want one of these instead:

[[ ${array[$i]} -gt $max ]]   # numeric comparison operator
(( ${array[$i]} > $max ))     # arithmetic evaluation

Or, use standard tools which will probably be faster despite having to spawn a couple of extra processes:

max=$( printf "%d\n" "${array[@]}" | sort -n | tail -1 )

Upvotes: 6

Related Questions