29

Possible Duplicate:
How to sort an array in BASH

I have numbers in the array 10 30 44 44 69 12 11.... How to display the highest from array?

echo $NUM //result 69
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Charlie
  • 2,061
  • 4
  • 21
  • 21
  • 1
    http://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash – paul Oct 05 '12 at 10:28
  • 1
    What have you tried so far? Try to follow the [rubber duck](http://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html) example. – AncientSwordRage Oct 05 '12 at 10:29

2 Answers2

62

You can use sort to find out.

#! /bin/bash
ar=(10 30 44 44 69 12 11)
IFS=$'\n'
echo "${ar[*]}" | sort -nr | head -n1

Alternatively, search for the maximum yourself:

max=${ar[0]}
for n in "${ar[@]}" ; do
    ((n > max)) && max=$n
done
echo $max
choroba
  • 231,213
  • 25
  • 204
  • 289
5

try this:

a=(10 30 44 44 69 12 11 100)

max=0
for v in ${a[@]}; do
    if (( $v > $max )); then max=$v; fi; 
done
echo $max

result in 100

  • Here's the same issue as in the answer above -- there's a problem with max=0 -- what if all args are negative? .. Here's a better solution -- https://stackoverflow.com/a/40719447/2107205 – mato Nov 21 '16 at 18:41