2

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.

2 Answers 2

6

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 )
Sign up to request clarification or add additional context in comments.

1 Comment

Sorting is overkill for finding the max, as it is an O(n lg n) operation compared to O(n) to find the max with a loop. Depending on the size of the list, though, you may not notice a difference, or the difference won't be worth worrying about.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.