Picking high and low variables in a bash script - possible?

Is it possible to have a bash script pick the highest and lowest values of four variables? I've been googling for this but haven't come up with anything. I have a script that assigns variables ($c0, $c1, $c2, and $c3) based on the coretemps from grep/sed statements of sensors. I'd like to also assign two new variables ($chigh and $clow) that will be the highest and lowest of the original four but I don't know how to go about it in bash.

Thanks!

You can do somthing like that :

c0=100
c1=12
c2=777
c3=1

clow=$c0
chigh=$c0

(( $c1 < $clow )) && clow=$c1
(( $c2 < $clow )) && clow=$c2
(( $c3 < $clow )) && clow=$c3

(( $c1 > $chigh )) && chigh=$c1
(( $c2 > $chigh )) && chigh=$c2
(( $c3 > $chigh )) && chigh=$c3

echo "Low : $clow"
echo "High: $chigh"

Output

Low : 1
High: 777

Jean-Pierre.

Another way ...

$clow=$(echo -e "$c0\n$c1\n$c2\n$c3" | sort -n | head -1)
$chigh=$(echo -e "$c0\n$c1\n$c2\n$c3" | sort -n | tail -1 )

check the man pages for sort. then once the data is sorted use sed to print out the first and last item.

here's an example using ls, i'll sort files by size then print the largest

mo@mo-laptop:~/scripts$ ls -l | awk '{ print $5 }' | sort -nr | sed -e '2,$d'
1366
mo@mo-laptop:~/scripts$

i used awk to strip everything out of the output except the file size. if your positional parameters are only number, this is unecessary

Or a variation on Aigles' script using a loop:

c0=100
c1=12
c2=777
c3=1
clow=$c0
for i in {0..3}; do
  eval "((c$i < clow)) && clow=\$c$i"
  eval "((c$i > chigh)) && chigh=\$c$i"
done
echo "Low : $clow"
echo "High: $chigh"

Thanks for the replies, all. I like chakrapani's code the best because it's only two lines :slight_smile: