Shell Script User Input Date Validation

1

How would I go about performing date validation on user input in a shell script? I want to notify the user if they enter the date in the wrong format. The correct format would be YYYYMMDD.

THE DOCTOR

Posted 2015-05-05T17:29:01.390

Reputation: 191

There is already a good post for this: http://stackoverflow.com/questions/18709962/bash-regex-if-statement

– rfportilla – 2015-05-05T17:58:07.787

Answers

2

This method treats input as a string then parses and tests it for proper formatting. In this form, I have it also checking if the fields in the date are correct, but you can remove those conditionals if you don't need them.

#!/bin/bash
echo -n "Enter the date as YYYYMMDD >"
read date
if [ ${#date} -eq 8 ]; then
    year=${date:0:4}
    month=${date:4:2}
    day=${date:6:2}
    month30="04 06 09 11"
    leapyear=$((year%4)) # if leapyear this is 0
    if [ "$year" -ge 1901 -a "$month" -le 12 -a "$day" -le 31 ]; then
            if [ "$month" -eq 02 -a "$day" -gt 29 ] || [ "$leapyear" -ne 0 -a "$month" -eq 02 -a "$day" -gt 28 ]; then
                    echo "Too many days for February... try again"; exit
            fi
            if [[ "$month30" =~ "$month" ]] && [ "$day" -eq 31 ]; then
                    echo "Month $month cannot have 31 days... try again"; exit
            fi
    else echo "Date is out of range"; exit
    fi
else echo "try again...expecting format as YYYYMMDD"; exit
fi
echo "SUCCESS!"
echo "year: $year  month: $month  day: $day"

Chris

Posted 2015-05-05T17:29:01.390

Reputation: 44

1

You might like the option to accept many formats and convert them to standard form; the date command can help:

$ day=$(unset day;
        until date -d "${day:-XXX}" '+%Y%m%d' 2>/dev/null
          do read -p "Which day? " day
        done)
Which day? 
Which day? weds 
Which day? friday
$ echo $day
20150508

Toby Speight

Posted 2015-05-05T17:29:01.390

Reputation: 4 090

I'm having trouble getting this to work at all. I read the date into a variable $YMD and that's where I want to proceed if the date is the right format, otherwise I'd want to prompt the user again to re-enter the date in the right format. – THE DOCTOR – 2015-05-05T19:59:24.610

Show us your code! The snippet above does something useful, but I can't (yet) see why it's not useful for you. – Toby Speight – 2015-05-06T16:55:33.573