lukabix22
lukabix22

Reputation: 85

user input date format verification in bash

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!

Upvotes: 8

Views: 15760

Answers (2)

runlevel0
runlevel0

Reputation: 2993

date -d "$date" +%Y-%m-%d 

The latter is the format, the -d allows an input date. If it's wrong it will return an error that can be piped to the bit bucket, if it's correct it will return the date.

The format modifiers can be found in the manpage of date man 1 date. Here an example with an array of 3 dates:

dates=(2012-01-34 2014-01-01 2015-12-24)

for Date in ${dates[@]} ; do
    if [ -z "$(date -d $Date 2>/dev/null)" ; then
       echo "Date $Date is invalid"
    else
       echo "Date $Date is valid"
    fi
done

Just a note of caution: typing man date into Google while at work can produce some NSFW results ;)

Upvotes: 3

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10673

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.

Upvotes: 30

Related Questions