0

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

Vishal
  • 65
  • 2
  • 9
  • 2
    You need to add dollar signs to all your variables except the ones in the `read` lines: eg `if [ $n1 -gt $n2 ]`. You also don't need extra brackets around your ifs, and need to be more careful with the spacing: `if [ $n1 -gt $n2 ] && [...]; then` – Josh Jolly Apr 14 '14 at 08:46
  • 1
    Also why you take so many `if..elif` It's shall script not `C`. So take advantage of it look http://stackoverflow.com/questions/12744245/bash-how-to-find-the-highest-number-in-array – Jayesh Bhoi Apr 14 '14 at 08:49
  • @Josh Jolly Thank you your guidance work for me. – Vishal Apr 14 '14 at 09:08
  • 1
    @Vishal, keep in mind that `[` is not just syntax, it's a **command** (from a bash prompt, enter `help [`) and like any other command, it requires whitespace before it and after. – glenn jackman Apr 14 '14 at 12:21

3 Answers3

2

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
chepner
  • 497,756
  • 71
  • 530
  • 681
user3132194
  • 2,381
  • 23
  • 17
1

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.

twalberg
  • 59,951
  • 11
  • 89
  • 84
1

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

mato
  • 593
  • 4
  • 11