sadboy sadboy - 24 days ago 8
Bash Question

Finding max and minimum values from a bash array

I have a txt file that has integer values written in it with a ";" separator.
117;92;16;20;

I need to compare these and select the highest one.
My code:

IFS=';' #Internat Field Separator
read -ra vector<$file
max=$vector[0]
min=$vector[0]

for i in ${vector[@]}
do

if [[ $i > $max ]] ; then
max=$i
fi

if [[ $i < $min ]] ; then
min=$i

fi
done
echo "Max value is $max, minimal value is $min"
break


The output is:


Max value is 92, minimal value is 16.


So of course this is wrong. When I try to echo it:

echo $value ( in a loop of course )


The output is


177[0] 92 16 25


Why does the first letter show as int[0]? Because of that I cannot compare them. I can't figure out anything....

Answer

Your trailing [0]s are caused by failing to use curly brackets in your parameter expansions. There's no need for them beyond clarity, anyhow -- referring to $vector expands the first element if vector is an array.

The largest issue here is that [[ $foo > $bar ]] compares these values as strings, not as numbers, hence 92 being larger than 166 (since it starts with 9 rather than 1). Use (( )) to enter a math context, in which < and > perform numeric comparisons and $ sigils are unnecessary surrounding variable names.

#!/usr/bin/env bash

IFS=';' read -ra vector <"$file"
max=${vector[0]}
min=${vector[0]}

for i in "${vector[@]}"; do
  (( i > max )) && max=$i
  (( i < min )) && min=$i
done

echo "Max value is $max, minimal value is $min"