We help IT Professionals succeed at work.

shell script - check for entering date in the correct format on the command line

Medium Priority
Last Modified: 2013-12-26
I'm writing a script that needs to have the date passed as a argument on the commnad line.  The date must be entered in the correct format, which in this case is, MM-DD-YYYY.  This also need to check to see if they even entered the date on the command line.

Does anyone have a snippet of code that will perform that check?


Watch Question

assuming programming in sh, use something like:

echo "$1" | awk -F- '($1!~/[0-1][0-9]/){print "bad month";exit(1)}($2!~/[0-3][0-9]/){print "bad day";exit(1)}($3!~/[1-9][0-9][0-9][0-9]/){print "bad year";exit(1)}'
[ $? -ne 0 ] && exit 1

# regex in awk to be improved in many ways ;-)

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts


Thanks, worked like a charm!


question - I put the code on separate lines to make it easier to read, breaking at the ";"  Would you explain how the scripts works?  If it's too much trouble for the amount of points I understand.



echo "$MDATE" | awk -F- '($1!~/[0-1][0-9]/){print "bad month"
exit(1)}($2!~/[0-3][0-9]/){print "bad day"
exit(1)}($3!~/[1-9][0-9][0-9][0-9]/){print "bad year"
awk splits each line (only one should reach) at the - into words (-F- option), then checks the words ($1, $2, $3) using a simple regex. If the regex does not macth it prints the message and exits awk with an status code 1.
My sample uses awk's status code to exit the script too:  [ $? -ne 0 ]
Take care that the suggested regex are lazy, it allows 19 as month ...

> .. put the code on separate lines ..
take care that this depends on your version of the shell, a human reader friendly version might be:

echo "$MDATE" | awk -F- '
  ($1!~/[0-1][0-9]/){ print "bad month"; exit(1) }
  ($2!~/[0-3][0-9]/){ print "bad day"; exit(1) }
  ($3!~/[1-9][0-9][0-9][0-9]/){ print "bad year"; exit(1) }

but I prefer onliners ;-)


Thank You!  It is easier for me to understand now - and I prefer multiliners  8^)
Our Solaris boxes have a ckdate shell command which does exactly what you're after, so could be incorporated into your script easily if available.  I mention this as the accepted answer above will not throw out 02/33/2006, 19/19/1999, 02/31/2006 etc.  ckdate will detect leap years as well.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.