Bash: How to Find Minimum and Maximum Values in Array


Often you may want to find the minimum and maximum values of an array in Bash.

You can use the following methods to do so:

Method 1: Find Minimum Value of Array

echo "${my_array[*]}" | sort -nr | tail -n1

This particular example will return the minimum value in the array named $my_array.

Method 2: Find Maximum Value of Array

echo "${my_array[*]}" | sort -nr | head -n1

This particular example will return the maximum value in the array named $my_array.

Note that both of these methods use sort -nr to first sort the values in the array in reverse order from largest to smallest.

We then use either tail or head to extract the first or last value from the array, which represents either the minimum or maximum value in the array, respectively.

The following examples show how to use both methods in practice.

Example 1: Find Minimum Value of Array in Bash

Suppose that we create an array in Bash named $my_array that contains several different numeric values.

We can use the following syntax to calculate the minimum value of this array:

my_array=(4 15 20 51 30 45 50 3 16 29 22)
IFS=$'\n'
echo "${my_array[*]}" | sort -nr | tail -n1

The following screenshot shows how to use this syntax in practice:

Bash find minimum value of array

From the output we can see that the minimum value of the array is 3.

Example 2: Find Maximum Value of Array in Bash

Suppose that we create an array in Bash named $my_array that contains several different numeric values.

We can use the following syntax to calculate the maximum value of this array:

my_array=(4 15 20 51 30 45 50 3 16 29 22)
IFS=$'\n'
echo "${my_array[*]}" | sort -nr | head -n1

The following screenshot shows how to use this syntax in practice:

Bash find maximum value of array

From the output we can see that the maximum value of the array is 51.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Calculate the Average of a Column
Bash: How to Round Numbers to 2 Decimal Places
Bash: How to Find Duplicate Lines in File

Leave a Reply