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.

1

2 Answers 2

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"
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
2
  • 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
    May 5, 2015 at 19:59
  • Show us your code! The snippet above does something useful, but I can't (yet) see why it's not useful for you. May 6, 2015 at 16:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .