In a linux shell script how to print the largest and smallest array values?

I am not very versed in arrays, but I need to know how to find and print the largest and smallest array values. The array is predefined by the read command, the user will be prompted to enter n number of integers.

How can I assign a read to an array and find and display the largest and smallest array values?

Is there a way to check the elements of an array to see if they are 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" 
+4
source share
3 answers

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

Some comments and explanations in a line (with a # prefix)

 # 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" 
+9
source

Try it if you need to compare (signed or not) INTEGERS :

 #!/bin/bash arr=( -10 1 2 3 4 5 ) min=0 max=0 for i in ${arr[@]}; do (( $i > max || max == 0)) && max=$i (( $i < min || min == 0)) && min=$i done echo "min=$min max=$max" 

OUTPUT

 min=-10 max=5 

EXPLANATION

+5
source

Funny way with sorting:

if you have an array of integers, you can use sort to sort it, then select the first and last elements for the min and max elements, for example:

 { read min; max=$(tail -n1); } < <(printf "%s\n" "${array[@]}" | sort -n) 

So, if you want to invite the user to 10 integers, make sure that the user has entered integers and then sorted them, you could do:

 #!/bin/bash n=10 array=() while ((n));do read -p "[$n] Give me an integer: " i [[ $i =~ ^[+-]?[[:digit:]]+$ ]] || continue array+=($i) ((--n)) done # Sort the array: { read min; max=$(tail -n1); } < <(printf "%s\n" "${array[@]}" | sort -n) # print min and max elements: echo "min=$min" echo "max=$max" 
+3
source

All Articles