Unix date format validation

660 views Asked by At

I wrote this small Unix shell script to validate the date format. My script should check whether the string is in YYYYMMDDHHMMSS format. If it is not in this format, it should send an error message.

For example, I declared an variable a and assigned a value to it.

a=20150620223405
date "+%Y%m%d%H%M%S" -d $a > /dev/null 2>&1
if [ $? -ne 0 ]
then
  echo "Invalid format"
else
  echo "Valid format"
fi 

It always shows as "Invalid format", I want to know what is the mistake here and how to proceed.

1

There are 1 answers

0
Oleg Andriyanov On

From man date:

DATE STRING

The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29 16:21:42" or even "next Thursday". A date string may contain items indicating cal‐ endar date, time of day, time zone, day of week, relative time, rela‐ tive date, and numbers. An empty string indicates the beginning of the day. The date string format is more complex than is easily documented here but is fully described in the info documentation.

And about format:

FORMAT controls the output.

This means that you cannot validate the date you pass as an argument. date validates it by itself regardless of format you supplied (as man says that FORMAT controls the output, not the input).

To validate the date i'd suggest you to use a regular expression and grep (1).