Vishal
Vishal

Reputation: 75

How to get greatest number out of 5 number using shell script

I am trying to find the greatest number from 5 given numbers in shell script. I am testing my code on Ideone.com in Bash category. I am getting error

Runtime error time: 0.02 memory: 5312 signal:-1

Here is the code

read -p "Enter first Number:" n1
read -p "Enter second Number:" n2
read -p "Enter third Number:" n3
read -p "Enter fourth Number:" n4
read -p "Enter fourth Number:" n5
if[ [ n1 -gt n2 ] && [ n1 -gt n2 ] && [ n1 -gt n3 ] && [ n1 -gt n4 ] && [ n1 -gt n5 ]] ; then
      echo "$n1 is a Greatest Number"
elif[ [ n2 -gt n3 ] && [ n2 -gt n3 ] && [ n2 -gt n4 ] && [ n2 -gt n5 ]] ; then
     echo "$n2 is a Greatest Number"
elif[ [ n3 -gt n4 ] && [ n3 -gt n5 ] ] ; then  
     echo "$n3 is a Greatest Number"
elif[ n4 -gt n5 ] ; then  
     echo "$n4 is a Greatest Number"
else
     echo "$n5 is a Greatest Number"
fi

What is the problem? kindly guide

Upvotes: 0

Views: 8742

Answers (3)

mato
mato

Reputation: 643

Here's a simple shell function to find max value out of numeric parameters passed:

max()
{
    local m="$1"
    for n in "$@"
    do
        [ "$n" -gt "$m" ] && m="$n"
    done
    echo "$m"
}

Example: max 1 3 2 returns 3

Upvotes: 1

twalberg
twalberg

Reputation: 62389

You could do it much more efficiently, without invoking external commands like sort and head / tail:

max2()
{ if (( "$1" > "$2" ))
  then
    echo "$1"
  else
    echo "$2"
  fi
}
max5()
{ tmp1=$(max2 "$1" "$2")
  tmp2=$(max2 "$3" "$4")
  tmp3=$(max2 "$tmp1" "$tmp2")
  echo $(max2 "$tmp3" "$5")
}
m=$(max5 "$n1" "$n2" "$n3" "$n4" "$n5")

If you know that all the numbers are small enough, you could use return $n instead of echo $n, and then capture return codes instead of the textual representations of the numbers.

Upvotes: 1

user3132194
user3132194

Reputation: 2547

It seems your problem is spaces. Add spaces after "if" "elif" and before "]"

And how about

echo -e "$n1 \n $n2 \n $n3 \n $n4 \n $n5" | sort -n -r | head -n 1

Upvotes: 2

Related Questions