Shell Script to Check if the Current Year is Leap Year or Not

shell script is a computer program designed to be run by the Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text. A script that sets up the environment, runs the program, and does any necessary cleanup, logging, etc. is called a wrapper.

In this post, we will write a shell script to check if the current year is a leap year or not.

INPUT:
none

OUTPUT:
Print “leap year” if the current year is leap year else print “not a leap year”

The following is the shell script to check if the current year is a leap year or not:

leap=$(date +"%Y")
echo taking year as $leap
if [ `expr $leap % 400` -eq 0 ]
then
echo leap year
elif [ `expr $leap % 100` -eq 0 ]
then
echo not a leap year
elif [ `expr $leap % 4` -eq 0 ]
then
echo leap year
else
echo not a leap year
fi

OUTPUT:

$ taking year as 2019
$ not a leap year

Let us know in the comments if you are having any questions regarding this shell script.

And if you found this post helpful, then please help us by sharing this post with your friends. Thank You

4 Comments

  1. Why we are used 400 and 100 in this program

    • because there are exceptions for leap year and just by mod 4 we can’t always get the right output.
      we basically have to check 3 conditions:
      mod 400
      mod 100
      mod 4

  2. Another approach to check if year is leap or not.

    leap=$(date +”%Y”)
    echo taking year as $leap
    Leapcheck=$(date -d “${leap}0229”

    if [ ${Leapcheck} = 0 ]
    then
    echo leap year
    else
    echo not a leap year
    fi

    This will work for systems that supports -d argument. Which can be checked by man date command.

  3. why did use leap =$(date +”%y”)

Leave a Reply

%d bloggers like this: