1

I have a array:

ARRAY=(12.5 6.2)

I wish to return the maximum value in ARRAY which Output is 12.5

Anyone can share me ideas?

I have try this:

max=0
for v in ${ARRAY[@]}; do
    if (( $v > $max )); then max=$v; fi; 
done
echo $max

But it return me:

((: 12.5 > 0 : syntax error: invalid arithmetic operator (error token is ".5 > 0 ")
((: 6.2 > 0 : syntax error: invalid arithmetic operator (error token is ".2 > 0 ")
2
printf '%s\n' "${ARRAY[@]}" |
awk '$1 > m || NR == 1 { m = $1 } END { print m }'

Since the bash shell does not do floating point arithmetics, it's easier to compare floating point numbers in another language. Here I'm using awk to find the maximum of all the elements in the ARRAY array.

The printf command will output each element of the array on its own line and the awk code will update its m value to be the maximum of the values seen so far. At the end, the m value is printed.

The test on NR == 1 will be true on for the first line read by the awk program and would initialise the value of m to the first value of the array (something that you fail to do, which means that your code would have returned 0 for an array with all negative numbers, had it worked).

5
  • Possible alternative to || NR == 1: set m to array's first element using -v m="${ARRAY}" – Olorin Jan 17 '19 at 6:56
  • Can your function here store in a variable? – Shi Jie Tio Jan 17 '19 at 6:57
  • @ShiJieTio I'm using no function, but the result may be stored in a variable using a standard command substitution as usual: max=$( printf ... | awk ... ). – Kusalananda Jan 17 '19 at 6:58
  • for example: Result= "%s\n' "${ARRAY[@]}" |awk '$1 > m || m == "" { m = $1 } END { print m }" – Shi Jie Tio Jan 17 '19 at 8:12
  • 1
    @ShiJieTio No. You left out the printf and the $( ... ) bit. – Kusalananda Jan 17 '19 at 8:14
0

If you want to do floating point arithmetics, you'd need to switch to ksh93, zsh or yash (or fish if you're ready to wander away from Bourne-like shells), bash doesn't support them.

For a syntax compatible to all 3 shells:

max() {
  [ "$#" -gt 0 ] || return
  typeset i max="$1"; shift
  for i do
    if [ "$((i > max))" -ne 0 ]; then
      max=$i
    fi
  done
  printf '%s\n' "$max"
}
array=(12.5 6.2 nan 0xfff -inf inf -1e12 1e20)
max "${array[@]}"

(you need a recent version of zsh for inf/nan to be supported. Variations in case are supported in all 3 (INF, NaN, Inf...), but only yash supports alternative spellings like Infinity; 0x12p34 types of numbers are not supported by zsh yet. Beware that whether 010 means 10 or 8 depends on the shell and its configuration)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.