In Linux shell script how do I print the largest and smallest values of an array?

bash, sh

Solution

The general idea is to iterate through the array once and keep track of what the `max` and `min` seen so far at each step.

Some comments and explanations in-line (prefixed by `#`)

# This is how to declare / initialize an array:
arrayName=(1 2 3 4 5 6 7)

# Use choose first element of array as initial values for min/max;
# (Defensive programming) - this is a language-agnostic 'gotcha' when
# finding min/max ;)
max=${arrayName[0]}
min=${arrayName[0]}

# Loop through all elements in the array
for i in "${arrayName[@]}"
do
    # Update max if applicable
    if [[ "$i" -gt "$max" ]]; then
        max="$i"
    fi

    # Update min if applicable
    if [[ "$i" -lt "$min" ]]; then
        min="$i"
    fi
done

# Output results:
echo "Max is: $max"
echo "Min is: $min"

Problem

I don’t really understand much about arrays, but I need to know how to find and print the largest and smallest values of an array. The array is predefined by a read command, and the user will be prompted to enter n amount of integers. How would I assign the read input to an array and find and display the largest and smallest values of the array? Is there a way to test the array elements to see if they are all integers? ``` #!/bin/bash read -a integers biggest=${integers[0]} smallest=${integers[0]} for i in ${integers[@]} do if [[ $i -gt $biggest ]] then biggest="$i" fi if [[ $i -lt $smallest ]] then smallest="$i" fi done echo "The largest number is $biggest" echo "The smallest number is $smallest" ```

Original source