13 January 2012

Shell Script to find Greatest of Three Number using if-else Statement

5 comments

Q. How do I write Shell Script to find Greatest of Three Numbers by If-else statement


Ans:

#!/bin/bash
echo "enter first number"
read first
echo "enter second number"
read sec
echo "enter third number"
read third
if [ $first -gt $sec ] ; then
if [ $first -gt $third ] ; then
echo -e " $first is greatest number "
else
echo -e " $third is greatest number "
fi
else
if [ $sec -gt $third ] ; then
echo -e " $sec is greatest number "
else
echo -e " $third is greatest number "
fi
fi


Output


shell script to find greatest of three numbers using if else statement

Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

5 comments:

  1. The below code can also serve the purpose

    echo "Enter the three numbers which are to be compared"
    read var1 var2 var3
    if [[ $var1 > $var2 ]] && [[ $var1 > $var3 ]];then
    echo "$var1 is gretest of three numbers"
    elif [[ $var2 > $var1 ]] && [[ $var2 > $var3 ]];then
    echo "$var2 is greatest of three number"
    elif [[ $var3 > $var1 ]] && [[ $var3 > $var2 ]];then
    echo "$var3 is gretaer of three numbers"
    else
    echo " All the three numbers are equal"
    fi

    ReplyDelete
    Replies
    1. This is not the right code for comparing three numbers. If I enter 2, 2, 1 as my three numbers, the o/p is 0.

      Here is the right code.

      # Creating a max function to get the max number
      max() {
      if [[ ( $q1 -eq $q2 ) && ( $q2 -eq $q3 ) ]] ; then
      retval=$q1
      fi
      if [[ ( $q1 -gt $q2 ) && ( $q1 -gt $q3 ) ]] ; then
      retval=$q1
      fi

      if [[ ( $q1 -gt $q2 ) && ( $q1 -lt $q3 ) ]] ; then
      retval=$q3
      fi

      if [[ ( $q2 -gt $q1 ) && ( $q2 -gt $q3 ) ]] ; then
      retval=$q2
      fi

      if [[ ( $q1 -gt $q2 ) && ( $q1 -eq $q3 ) ]] ; then
      retval=$q1
      fi

      if [[ ( $q1 -eq $q2 ) && ( $q1 -lt $q3 ) ]] ; then
      retval=$q3
      fi

      if [[ ( $q1 -lt $q2 ) && ( $q2 -eq $q3 ) ]] ; then
      retval=$q2
      fi

      if [[ ( $q1 -eq $q2 ) && ( $q2 -gt $q3 ) ]] ; then
      retval=$q2
      fi

      return $retval
      }

      Delete
  2. How do you print out the three numbers in decending order?

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete