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. By the end of this tutorial, you will have a working shell script that can accurately validate dates and handle leap years.

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. Along the way, we will explain each code snippet and provide examples to help you understand the process clearly.

Checking the Validity of the Year

To begin, let's focus on validating the year entered by the user. We will ensure that the year is a four-digit number and falls within a reasonable range. Here's the code snippet to accomplish this −

#!/bin/bash

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

# Extracting the year from the input
year=${input_date:0:4}

# Checking the validity of the year
if [[ ! $year =~ ^[0-9]{4}$ ]]; then
    echo "Invalid year format. Please enter a valid date."
    exit 1
fi

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

In the above code, we start by prompting the user to enter a date using the `read` command. Then, we extract the year from the input by using parameter expansion `${input_date:0:4}`, which takes the first four characters from the input. We use a regular expression `^[0-9]{4}$` to check if the year is a four-digit number.

If the year format is invalid, we display an error message and exit the script with a status code of 1. Additionally, we validate the range of the year by comparing it with the current year obtained using the `date +%Y` command. If the year is not within the range of 1900 to the current year, we display an appropriate error message and exit the script.

Output

Enter a date (YYYY-MM-DD): 2024-07-15
Invalid year. Please enter a year between 1900 and 2023.

Enter a date (YYYY-MM-DD): abc-07-15
Invalid year format. Please enter a valid date.

Validating the Month

Next, let's move on to validating the month entered by the user. We will check if the month is a two-digit number between 01 and 12. Here's the code snippet 

# Extracting the month from the input
month=${input_date:5:2}

# Checking the validity of the month
if [[ ! $month =~ ^[0-9]{2}$ || month -lt 1 || month -gt 12 ]]; then
    echo "Invalid month. Please enter a valid date."
    exit 1
fi

In the code above, we extract the month from the input by using parameter expansion `${input_date:5:2}`, which takes the two characters starting from index 5 in the input. We then use a regular expression `^[0-9]{2}$` to check if the month is a two-digit number.

If the month format is invalid or the month is not within the range of 01 to 12, we display an error message and exit the script. This ensures that the entered date has a valid month.

Output

Enter a date (YYYY-MM-DD): 2023-15-07
Invalid month. Please enter a valid date.

Enter a date (YYYY-MM-DD): 2023-00-07
Invalid month. Please enter a valid date.

Verifying the Day

Moving forward, let's focus on verifying the day entered by the user. We will consider the number of days in each month, accounting for leap years. Here's the code snippet −

# Extracting the day from the input
day=${input_date:8:2}

# Checking the validity of the day
if [[ ! $day =~ ^[0-9]{2}$ || day -lt 1 ]]; then
    echo "Invalid day. Please enter a valid date."
    exit 1
fi

# Determining the number of days in the month
days_in_month=$(cal $month $year | awk 'NF {DAYS = $NF}; END {print DAYS}')

# Handling February in leap years
if (( month == 2 && year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) )); then
    days_in_month=29
fi

# Checking if the day is within the valid range
if (( day > days_in_month )); then
    echo "Invalid day. Please enter a valid date."
    exit 1
fi

In the code snippet above, we extract the day from the input using parameter expansion `${input_date:8:2}`, which takes the two characters starting from index 8 in the input. We check if the day is a two-digit number and greater than or equal to 1.

To determine the number of days in the month, we utilize the `cal` command, which generates a calendar for the specified month and year. We pass the month and year as arguments to `cal` and use `awk` to extract the last non-empty field, which represents the number of days in the month.

Next, we handle the special case of February in leap years. We check if the month is February (month == 2) and if the year is divisible by 4 but not divisible by 100 unless it is divisible by 400. If these conditions are met, we set the `days_in_month` variable to 29, indicating that February has 29 days in a leap year.

Finally, we compare the entered day with the calculated number of days in the month. If the day exceeds the valid range, we display an error message and exit the script.

Output

Enter a date (YYYY-MM-DD): 2023-02-30
Invalid day. Please enter a valid date.

Enter a date (YYYY-MM-DD): 2024-02-29
Entered date is valid: 2024-02-29

Validating the Complete Date

In the last section, let's combine all the validations and check the complete date entered by the user. Here's the code snippet:


# Checking the validity of the complete date
if [[ ! $input_date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
    echo "Invalid date format. Please enter

 a valid date."
    exit 1
fi

# Printing the validated date
echo "Entered date is valid: $input_date"

In this code snippet, we check if the complete date matches the desired format using the regular expression `^[0-9]{4}-[0-9]{2}-[0-9]{2}$`. If the format is invalid, we display an error message and exit the script.

If the date format is valid, we print a success message along with the validated date.

Output

Enter a date (YYYY-MM-DD): 2023-07-15
Entered date is valid: 2023-07-15

Enter a date (YYYY-MM-DD): abc
Invalid date format. Please enter a valid date.

Conclusion

In this tutorial, we have developed a shell script that validates dates, taking into account the rules of leap years. By breaking down the problem into smaller steps, we were able to create an efficient script that prompts the user to enter a date and performs various checks to ensure its validity. Shell scripting allows us to automate tasks and handle complex operations, making it a valuable tool for Linux users. With the knowledge gained from this tutorial, you can now create your own shell scripts to validate dates or perform other useful tasks.

Updated on: 28-Jul-2023

605 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements