In this tutorial, I will show you a simple shell script to check whether a given number provided through command line denotes a leap year or not using shell script. Algorithm is fairly simple
- Check whether the number of command line arguments are equal to 1 or not
- If not equal to 1, then print an error message and exit, otherwise proceed to next step.
- Store the value of the remainder by dividing number provided through terminal by 4. i.e
check=`expr $1 % 4` - Now check whether the value of this
checkvariable is equal to 0 or not. If it is equal to 0 then provided number is a leap year, otherwise not.
Instructions:
- Tell the terminal to user bash shell to execute the program using the following line of code.
#!/bin/bash
- Now check whether the number of arguments supplied are equal to 1 or not. If not, then print an error message and exit.
if [ $# -ne 1 ] then echo "Usage : $0" echo "Script to check whether a year is leap year or not" echo "Enter a single year to check" exit 1 fi - Now assign the remainder of number supplied divided by 4 to a variable named
check.
check=`expr $1 % 4`
- Now check whether the value of this variable
checkis equal to 0 or not, if it is then the number supplied is a leap year, otherwise not.
if [ $check -ne 0 ] then echo "$1 is not a leap year" else echo "$1 is a leap year" fi
Here is a screenshot of the working of this script.
You can download the sample script from here.
Related posts:
How To Find Sum of Sum of digits of a number using Shell Scripting How To reverse the digits of a number using Shell Scripting How To find out Biggest number among the three provided numbers through command line using Shell Scripting How To Find Sum of Two Numbers which are supplied as Command Line Arguments How to validate date in PHP

Great post indeed.The idea is just so apt.