How To Ideas | How To Articles | How To Tutorials


1

How to check for leap year in Shell Script


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

  1. Check whether the number of command line arguments are equal to 1 or not
  2. If not equal to 1, then print an error message and exit, otherwise proceed to next step.
  3. Store the value of the remainder by dividing number provided through terminal by 4. i.e check=`expr $1 % 4`
  4. Now check whether the value of this check variable is equal to 0 or not. If it is equal to 0 then provided number is a leap year, otherwise not.

Instructions:

  1. Tell the terminal to user bash shell to execute the program using the following line of code.
    #!/bin/bash
  2. 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
  3. Now assign the remainder of number supplied divided by 4 to a variable named check.
    check=`expr $1 % 4`
  4. Now check whether the value of this variable check is 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.

Check Leap Year using Shell Script

Check Leap Year using Shell Script

You can download the sample script from here.

Filed in: Shell Scripting Tags: , , , , , , ,

One Response to "How to check for leap year in Shell Script"

  1. amit ganguly says:

    Great post indeed.The idea is just so apt.

Leave a Reply

Submit Comment



© 7643 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.