Thursday, March 13, 2014

Check if the given number is even or odd - Linux Shell Scripting

Problem Question


Write a script to check whether the given no. is even/odd

Explanation of Problem


Here we wish to write a Linux Shell Script that checks if the first number passed as command line argument is even or odd. So when executing the script EvenOdd.sh as under:

sh EvenOdd.sh 1

should give the answer as 1 is odd

and when run as

sh EvenOdd.sh 2

should give the output as 2 is even

Code



#*Even Odd Check*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 13-03-2014

x=`expr $1 % 2`
if [ $x -eq 0 ]
  then
   echo $1 is even
else
 echo $1 is odd
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.

x=`expr $1 % 2` -> We introduce a new variable 'x' to our shell. Then, we tell it to assign 'x' the value that follows the '=' sign. The shell then encounters `` which makes it understand the expression inside will return something that has to be assigned to 'x'. Then we tell it that this is an expression, by using the keyword 'expr' which is followed by the expression. Note that the whole expression is quoted as `expr YOUR EXPRESSION`. Then we assign the expression as Command Line Argument 1(implied by $1) modulus 2. We apply the modulus operator (%) and thus we find the remainder when we divide $1 by 2.

if [ $x -eq 0 ] -> Here we have our if block. The condition says if $x is zero. Note that now we use a $ sign with x since the variable is already declared. If a number is even, it will give a remainder zero when divided by 2, else not. This is what we check.

then -> follows the code that has to executed in case the if condition is true. That means the remainder on dividing the first command line argument with 2 is zero. Thus we print $1 is even.

else -> Starts our else block executed in case the if condition fails. That means the remainder ain't zero when we divide $1 by 2. Thus we print $1 is odd.

echo -> Linux shell command used to print to standard output, the terminal display.

fi -> End of the if block.

Output(s)



No comments:

Post a Comment

Need help?