user input date format verification in bash

bash, date, validation

Solution

Using regex:

if [[ $date =~ ^[0-9]{4}-[0-3][0-9]-[0-1][0-9]$ ]]; then

or with bash globs:

if [[ $date == [0-9][0-9][0-9][0-9]-[0-3][0-9]-[0-1][0-9] ]]; then

Please note that this regex will accept a date like `9999-00-19` which is not a correct date. So after you check its possible correctness with this regex you should verify that the numbers are correct.

IFS='-' read -r year day month <<< "$date"

This will put the numbers into `$year` `$day` and `$month` variables.

Problem

So I'm trying to write a simple script in bash that asks user for input date in following format (YYYY-dd-mm). Unfortunately I got stuck on first step, which is verifying that input is in correct format. I tried using 'date' with no luck (as it returns actual current date). I'm trying to make this as simple as possible. Thank you for your help!

Original source