Shell Script to Validate the Date, Considering Leap Year Rules

In this tutorial, we will explore how to create a shell script that validates dates, taking into account the rules of leap years. We will be using the Linux operating system and the Bash shell scripting language for this purpose. Shell scripting allows us to automate tasks and perform complex operations by writing simple and efficient scripts.

We will develop a shell script that prompts the user to enter a date in the format YYYY-MM-DD and then validates whether the entered date is valid or not, considering leap year rules. We will break down the problem into smaller steps and gradually build our script to achieve the desired functionality.

Understanding Leap Year Rules

Before diving into the script, let's understand the leap year rules:

  • A year is a leap year if it is divisible by 4

  • However, if the year is divisible by 100, it is not a leap year

  • Exception: if the year is divisible by 400, it is a leap year

For example, 2000 is a leap year (divisible by 400), but 1900 is not (divisible by 100 but not by 400).

Complete Date Validation Script

#!/bin/bash

# Function to check if a year is a leap year
is_leap_year() {
    local year=$1
    if (( year % 400 == 0 )); then
        return 0  # True
    elif (( year % 100 == 0 )); then
        return 1  # False
    elif (( year % 4 == 0 )); then
        return 0  # True
    else
        return 1  # False
    fi
}

# Prompting the user to enter a date
read -p "Enter a date (YYYY-MM-DD): " input_date

# Check if the input matches the expected format
if [[ ! $input_date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
    echo "Invalid date format. Please enter a date in YYYY-MM-DD format."
    exit 1
fi

# Extracting year, month, and day from the input
year=${input_date:0:4}
month=${input_date:5:2}
day=${input_date:8:2}

# Remove leading zeros for numeric comparison
month=$((10#$month))
day=$((10#$day))

# Validating the year (reasonable range)
current_year=$(date +%Y)
if (( year < 1900 || year > current_year + 100 )); then
    echo "Invalid year. Please enter a year between 1900 and $((current_year + 100))."
    exit 1
fi

# Validating the month
if (( month < 1 || month > 12 )); then
    echo "Invalid month. Please enter a month between 01 and 12."
    exit 1
fi

# Validating the day
if (( day < 1 )); then
    echo "Invalid day. Day must be at least 01."
    exit 1
fi

# Define days in each month
days_in_month=(31 28 31 30 31 30 31 31 30 31 30 31)

# Check for leap year and adjust February
if is_leap_year $year; then
    days_in_month[1]=29  # February in leap year
fi

# Get maximum days for the given month
max_days=${days_in_month[$((month-1))]}

# Check if day is valid for the given month
if (( day > max_days )); then
    echo "Invalid day. Month $month has only $max_days days in year $year."
    exit 1
fi

echo "Entered date is valid: $input_date"
if is_leap_year $year; then
    echo "Note: $year is a leap year."
fi

Step-by-Step Validation Process

The script follows these validation steps:

  1. Format Check Ensures the input matches YYYY-MM-DD pattern using regex

  2. Year Validation Checks if year is within a reasonable range (1900 to current year + 100)

  3. Month Validation Verifies month is between 1 and 12

  4. Day Validation Confirms day is at least 1 and not exceeding the maximum days for that month

  5. Leap Year Handling Adjusts February to have 29 days in leap years

Example Usage

$ bash date_validator.sh
Enter a date (YYYY-MM-DD): 2024-02-29
Entered date is valid: 2024-02-29
Note: 2024 is a leap year.

$ bash date_validator.sh  
Enter a date (YYYY-MM-DD): 2023-02-29
Invalid day. Month 2 has only 28 days in year 2023.

$ bash date_validator.sh
Enter a date (YYYY-MM-DD): 2023-13-01
Invalid month. Please enter a month between 01 and 12.

$ bash date_validator.sh
Enter a date (YYYY-MM-DD): abc-01-01
Invalid date format. Please enter a date in YYYY-MM-DD format.

Key Features

  • Leap Year Function Implements the complete leap year logic as a reusable function

  • Leading Zero Handling Uses $((10#$variable)) to handle leading zeros in numeric comparisons

  • Days Array Pre-defines days in each month for efficient validation

  • Comprehensive Error Messages Provides specific feedback for different validation failures

Conclusion

This shell script provides a robust solution for date validation that properly handles leap years according to Gregorian calendar rules. The modular approach with a dedicated leap year function makes the code maintainable and easy to understand. With this script, you can accurately validate dates and ensure data integrity in your applications.

Updated on: 2026-03-17T09:01:39+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements