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

4
  • 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, 2014 at 8:46
  • 1
    Also why you take so many if..elif It's shall script not C. So take advantage of it look stackoverflow.com/questions/12744245/… Apr 14, 2014 at 8:49
  • @Josh Jolly Thank you your guidance work for me.
    – Vishal
    Apr 14, 2014 at 9: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. Apr 14, 2014 at 12:21

3 Answers 3

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
1
  • 5
    printf "%s\n" $n1 $n2 $n3 $n4 $n5 is tidier than echo -e ... Apr 14, 2014 at 12:20
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.