Wednesday, March 12, 2014

Find the greatest of three numbers (passed as command line parameters) - Linux Shell Scripting

Problem Question


Write a script to find the greatest of three numbers (numbers passed as command line parameters)

Explanation of Problem


We need to write a Linux Shell Script that when executed, will find the greatest of the three numbers. These numbers should be passed as command line arguments. This means that, if the name of our script is GreatestOfThree.sh, then we execute it as under to get the result:

sh GreatestOfThree.sh 23 121 1

and the result should be 121

Code




#*Greatest of Three Numbers*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 12-03-2014

if [ $1 -gt $2 ]
 then
  if [ $1 -gt $3 ]
  then
   echo $1 is the greatest
  else
   echo $3 is the greatest
fi
else
 if [ $2 -gt $3 ]
  then
   echo $2 is the greatest
  else
   echo $3 is the greatest
 fi
fi

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

$1, $2, ... $n -> The nth command line argument
if [ x -gt y ] -> -gt check if the argument before it is greater than the one that follows it.
then -> In case the 'if' condition passes, this part of code is executed that follows 'then'
else -> In case the 'if' condition fails, this part of code is executed that follows 'else'
fi -> Closes the 'if' or 'if-else' block

In the code above what we did is, first we checked if the first command line argument is greater than the second, if yes, we check if it is greater than the third. If this is also true, we print the first argument using '$1' followed by the phrase is the greatest. If the second if block fails, it means that $1>$2, but $1<$3 => $3 is the greatest. Then, we print the third argument using '$3' followed by the phrase is the greatest.

If the first if block fails, then we compare second and third argument. After testing again, we do the same thing as above.

Output(s)




No comments:

Post a Comment

Need help?