Showing posts with label bash script leap year. Show all posts
Showing posts with label bash script leap year. Show all posts

Thursday, September 4, 2014

Leap Year Checker in Bash

In this article I would like to share with you a simple bash script that I wrote to check if the given year by the user is a leap year or not a leap year. In order for us to understand leap year occurs every four years just like the Olympic games examples of leap year are 1988, 2000, 2004, 2008 and etc. 

The formula in bash script in checking for leap year is a=$(($year % 4)) in this expression we assign a variable a to check if the given year that is being stored in variable year has a remainder of 4. The operator we use to check of remainder is % also known as modulo. If assignment operator a is equal to without any remainder in the given year that year will become a leap year. In addition our script will allow the user to repeat the program running by asking the user if the user would like to run the program again or not. What is good about this script it checks if the response of the user to run the program is valid or not valid it makes our script more secure in accepting only valid response from our user.

I hope you will find our program useful in your learning how to write bash script in Linux and Unix operating system. If you have some questions please send me an email at jakerpomperada@yahoo.com and jakerpomperada@gmail.com.

Thank you very much.



Sample Output of Our Program


The nano text editor used in writing our script.


Program Listing

#!/bin/bash

# Leap Year Checker
# Written By Mr. Jake R. Pomperada, MAED-IT
# Operating System : UBUNTU 14.04
# Date : September 4, 2014 Thursday

start()
{
echo -e "\n"
echo -e "\t (====== LEAP YEAR CHECKER =====)";
echo -e "\n"

read -p  "Please enter a year : " year
echo -e "\n"

a=$(($year % 4))
b=$(($year % 100))
c=$(($year % 400))


if [[ $a == 0 || $b == 0 || $c == 0 ]]; then
   echo "The $year is a Leap Year."
else
   echo  "The $year is Not a Leap Year"
fi
while true; do
  echo -e "\n"
  read -p "More (Y/N)? " answer
  case $answer in
       [Yy]* ) start;  break;;
       [Nn]* ) bye; break;;
       * ) echo "Please answer yes or no. ";;
  esac
done
}

bye()
{
echo -e "\n"
echo -e "\t Thank You For Using This Program.";
echo -e "\n\n";
}

start

DOWNLOAD FILE HERE