0

I have an array of floats in Bash:

For example:

array(1.0002, 1.00232, 1.3222, ....)

I want to find the maximum and the minimum element of the array using Bash. The problem with this is that I have float elements that are not quite supported in Bash.

I have tried for example:

IFS=$'\n'
echo "${ar[*]}" | sort -nr | head -n1

But it does not work for floats.

What is the best way to do this?

1
  • 2
    Please show what you tried and explain why it does not work as expected. Commented Aug 4, 2021 at 13:04

2 Answers 2

3

There are probably many ways and I don't claim the two following are "the best".

You could use a calculator that supports floats, like bc, for instance:

max="${array[0]}"
min="${array[0]}"
for v in "${a[@]}"; do
  max=$(echo "if($v>$max) $v else $max" | bc)
  min=$(echo "if($v<$min) $v else $min" | bc)
done
echo "max=$max"
echo "min=$min"

awk also supports floats, so the following would do the same:

printf '%s\n' "${array[@]}" | \
awk '$1>max||NR==1 {max=$1}
     $1<min||NR==1 {min=$1}
     END {print "max=" max; print "min=" min}'
Sign up to request clarification or add additional context in comments.

4 Comments

The first one gives me a syntax error, the second one works perfectly. Thanks!
@epushor What syntax error? Do you have bc installed? Do you have non-numeric values in your array?
the error is: (standard_in) 1: syntax error - that is all I get. I only have floats in my array.
Hmm, strange. Could be a bc error message. What version of bc do you have (what is the output of bc --version)?
1
$array=(1.0002 1.00232 1.3222)        
$printf "%s\n" "${array[@]}" | sort -rn | head -n1        
1.3222          
$ printf "%s\n" "${array[@]}" | sort -rn | tail -n1  
1.0002  
#Tried with %s or %f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.