Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an easy way to find the lowest and highest number in a set of variables with values? (Bash script) (Linux)

#!/usr/bin/bash
for i in {1..10}
do
      read integer”$i”
done
sum=$((integer1+integer2+integer3+integer4+integer5+integer6+integer7+integer8+integer9+integer10))
echo Sum is $sum

I don’t know how to find the highest/lowest of the 10 variables and output them.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Compute the sum, max and min on the fly, as you would do in any programming language. And prefer an indexed array to store your integers (and access to their value with ${integer[1]}, ${integer[2]},...:

#!/usr/bin/bash
declare -ai integer=()
declare -i max min sum
for i in {1..10}; do
  read integer[i]
  if (( i == 1 )); then
    max="${integer[i]}"
    min="${integer[i]}"
    sum="${integer[i]}"
  else
    (( max = integer[i] > max ? integer[i] : max ))
    (( min = integer[i] < min ? integer[i] : min ))
    (( sum += integer[i] ))
  fi
done
printf 'max is %d\n' "$max"
printf 'min is %d\n' "$min"
printf 'sum is %d\n' "$sum"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading