1

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.

3
  • 4
    Is this home work? What code have you written so far? How do you gather the input? Please be more specific with questions. Post your code. Let readers know what you have tried. This is not a place for free answers. Commented Nov 26, 2013 at 1:08
  • little hint: stackoverflow.com/questions/12882089/… Commented Nov 26, 2013 at 1:29
  • No it's not homework. Code i have came up to till now is: #!/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 Commented Nov 26, 2013 at 1:35

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.