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

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

by Anup Maurya
15 minutes read

Ever wondered how to check if the current year is a leap year with a simple script? Well, wonder no more! In this post, we’ll write a Shell Script to Check if the Current Year is Leap Year or Not.

Leap Year Rules

A year is considered a leap year if it follows these rules:

  • Divisible by 4: Every year that is evenly divisible by 4 is a leap year (except for the special cases below).
  • Divisible by 100 (but not 400): Years divisible by 100 but not by 400 are not leap years.
  • Divisible by 400: Years divisible by 400 are leap years (e.g., 1600, 2000).

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

Here’s a shell script that checks for leap years

#!/bin/bash

# Get the current year
current_year=$(date +"%Y")

# Check if divisible by 400 (most specific case)
if [[ $current_year % 400 -eq 0 ]]; then
  echo "$current_year is a leap year."
  exit 0
fi

# Check if divisible by 100 (but not 400)
if [[ $current_year % 100 -eq 0 ]]; then
  echo "$current_year is not a leap year."
  exit 0
fi

# Check if divisible by 4 (general case)
if [[ $current_year % 4 -eq 0 ]]; then
  echo "$current_year is a leap year."
  exit 0
fi

# If none of the above conditions are met, it's not a leap year
echo "$current_year is not a leap year."

Explanation

  1. The script starts with #!/bin/bash, indicating the shell interpreter to use.
  2. current_year=$(date +"%Y") captures the current year using the date command with the %Y format specifier.
  3. The script then uses a series of if statements to check the leap year conditions:
    • The first if checks for divisibility by 400 (the most specific case, superseding the general divisibility by 4).
    • The second if checks for divisibility by 100 but not 400 (to exclude centuries not divisible by 400).
    • The third if checks for the general case of divisibility by 4.
  4. Each if statement displays a message and exits the script (using exit 0) upon finding a match.
  5. If none of the conditions are met, the final echo statement indicates the year is not a leap year.

Running the Script

  1. Save the script as a file (e.g., leap_year.sh).
  2. Make the script executable using chmod +x leap_year.sh.
  3. Run the script with ./leap_year.sh.

The script will output a message indicating whether the current year is a leap year or not.

related posts

Leave a Comment

Enable Notifications OK No thanks