I have script containin 4 variables. Need a function that will take values of those 4 variables and return name of the one that has lowest value.
So let's say that i have:
var1=55
var2=71
var3=30
var4=42
then i would like it to return as an answer: var3
Can anyone help? I need easiest way to solve that but appreciate any working solution.
1 Answer
From your question I don't think your values are in an array and that you want to know which index in the array is smallest - I think your values are in individual variables and you want to know the name of the variable containing the smallest value. If that is really what you are asking try this:
func()
{
minvar=$1
eval minval=\$$1
for i in $*
do
eval var=\$$i
# echo $i=$var
if [[ $var -lt $minval ]]
then
minvar=$i
minval=$var
# echo min=$i
fi
done
}
var1=55
var2=71
var3=30
var4=42
func var1 var2 var3 var4
echo $minvar=$minval
1 Comment
Grzegorz
Seem to work as i need, but I need to investigate it further, Im beginer and im not familiar with
\$$1 or \$$i don't know what it does actually. But yeah it finds smallest variable so I can move on.
#!/bin/bash x=12 y=35 z=7 q=24 va=0 vb=0 na=0 nb=0 minval=0 minname=0 if (( $x < $y )) ; then va=$x na=x ; else va=$y na=y ; fi if (( $z < $q )) ; then vb=$z nb=z ; else vb=$q nb=q ; fi if (( $va < $vb )) ; then minval=$va minname=$na ; else minval=$vb minname=$nb ; fi echo $minval echo $minname