Skip to main content

Date Validation in a Shell Script

Well I had numerous occasions to verify something at input of a ksh script.  This could be a date or number of particular string etc.
The most useful commands here are  "grep -E -q"  which returns a return code based on the search condition.  Exploiting this logic, please find sample Date Validation check in ksh shell script
# Date should fall in 2010-01-01  to 2019-12-31
# Script expecting a Date parameter in YYYYMMDD format as input
# This is not a 100% check, but will cover 99% of the scenario's

if [ $# -eq 1 ]
then
echo ${DateFormatInput} | grep -E -q '^201[1-9][01][0-9][0-3][0-9]$'
if [[ $? != 0 ]]; then
echo "Please enter Date in YYYYMMDD format. You Entered $@ "
echo "Quitting.. No action done..."
exit 0
fi
else
echo "Please enter Date as parameter in YYYYMMDD format"
echo "Quitting.. No action done..."
exit 0
fi

This script is useful especially when users enter various formats of date. Like UK employees use dd/mm/yyyy and some use mmddyyyy or some use yymmdd. This check will make users consistent in all your scripts.
grep -E -q '^201[1-9][01][0-9][0-3][0-9]$'
^ -> shows it should start with 201
$ -> means it should end with [0-9] character