Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Linux shell script how do i print the largest and smallest values of a array?

Tags:

bash

sh

I dont 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, 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"
like image 490
BobbyT28 Avatar asked Dec 01 '22 20:12

BobbyT28


1 Answers

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"
like image 91
sampson-chen Avatar answered May 19 '23 01:05

sampson-chen