Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 537
lukabix22 Avatar asked Sep 11 '13 18:09

lukabix22


2 Answers

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.

like image 60
Aleks-Daniel Jakimenko-A. Avatar answered Feb 03 '23 09:02

Aleks-Daniel Jakimenko-A.


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 ;)

like image 44
runlevel0 Avatar answered Feb 03 '23 07:02

runlevel0