Articles

Shell Script to Find A Number is Even or Odd

Shell Script to Find A Number is Even or Odd

In this shell script, we are going to:

  • solve how to write code to check a number is even or odd in shell script.

SHELL SCRIPT ODD EVEN STEPS:

  • 'clear' command to clear the screen.
  • Read a number which will be given by user.
  • Use `expr $n % 2`. If it equal to 0 then it is even otherwise it is odd.
  • Use if-else statements to make this program more easier.
  • Must include 'fi' after written 'if-else' statements.

EVEN OR ODD IN SHELL SCRIPT:

Given below is the steps check a number whether even or odd in shell script:
# HOW TO FIND A NUMBER IS EVEN OR ODD IN SHELL SCRIPT
# WRITTEN BY SURAJ MAITY
# TUTORIALSINHAND.COM
clear 
echo "---- EVEN OR ODD IN SHELL SCRIPT -----"
echo -n "Enter a number:"
read n
echo -n "RESULT: "
if [ `expr $n % 2` == 0 ]
then
	echo "$n is even"
else
	echo "$n is Odd"
fi

WRITTEN IN CYGWIN:

 

 OUTPUT:

FIND A NUMBER IS EVEN OR ODD IN SHELL SCRIPT - output

---- EVEN OR ODD IN SHELL SCRIPT -----

Enter a number:23
RESULT: 23 is Odd

 

If you face any problem regarding writing code or running problem, just follow these steps ->

RUN PROGRAM IN SHELL SCRIPT

EXPLANATION:

-----------------------------

FOR EVEN NUMBER

-----------------------------

Suppose, user enter 10.

if( n%2 ==0 ) then it will print even number because of we divide 10 by 2 then remainder must be 0.

i.e (10 %2 == 0), so, it is even number

----------------------------

FOR ODD NUMBER

----------------------------

Suppose, user enter 13.

if( n%2 !=0 ) then it will print odd number because of we divide 13 by 2 then remainder must not be 0.

i.e (13 %2 != 0), so, it is odd number.


Shell Script Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Suraj Maity
Page Views :    Published Date : Dec 13,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!