S1234
S1234

Reputation: 1

Date validation in Unix shell script (ksh)

I am validating the date in Unix shell script as follow:

CheckDate="2010-04-09"
regex="[1-9][0-9][0-9][0-9]-[0-9][0-9]-[0-3][0-9]"

if [[ $CheckDate = *@$regex ]]
then
echo "ok"
else
echo "not ok"
fi 

But ksh it is giving output as not okay.. pls help.. i want output as ok

Upvotes: 0

Views: 1890

Answers (3)

FanDeLaU
FanDeLaU

Reputation: 357

Here is my little script (written in Solaris 10, nawk is mandatory... sorry...). I know if you try to trick it by sending an alphanumeric you get an error on the let statements. Not perfect, but it gets you there...

#!/usr/bin/ksh

# checks for "-" or "/" separated 3 field parameter...   
if [[ `echo $1 | nawk -F"/|-" '{print NF}'` -ne 3 ]]
then
    echo "invalid date!!!"
    exit 1
fi

# typeset trickery...
typeset -Z4 YEAR
typeset -Z2 MONTH
typeset -Z2 DATE

let YEAR=`echo $1 | nawk -F"/|-" '{print $3}'`
let MONTH=`echo $1 | nawk -F"/|-" '{print $1}'`
let DATE=`echo $1 | nawk -F"/|-" '{print $2}'`
let DATE2=`echo $1 | nawk -F"/|-" '{print $2}'`

# validating the year
# if the year passed contains letters or is "0" the year is invalid...
if [[ $YEAR -eq 0 ]]
then
    echo "Invalid year!!!"
    exit 2
fi

# validating the month
if [[ $MONTH -eq 0 || $MONTH -gt 12 ]]
then
    echo "Invalid month!"
    exit 3
fi

# Validating the date
if [[ $DATE -eq 0 ]]
then
    echo "Invalid date!"
    exit 4
else
    CAL_CHECK=`cal $MONTH $YEAR | grep $DATE2 > /dev/null 2>&1 ; echo $?`
    if [[ $CAL_CHECK -ne 0 ]]
    then
        echo "invalid date!!!"
        exit 5
    else
        echo "VALID DATE!!!"
    fi
fi

Upvotes: 1

Ajinkya
Ajinkya

Reputation: 83

Please find the below code works as your exception.

  export checkdate="2010-04-09"
    echo ${checkdate} | grep '^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$'
    if [ $? -eq 0 ]; then
         echo "Date is valid"
     else
          echo "Date is not valid"
     fi

Upvotes: 0

Ajinkya
Ajinkya

Reputation: 83

You can try this and manipulate

  echo "04/09/2010" | awk  -F '/' '{ print ($1 <= 04 && $2 <= 09 && match($3, /^[0-9][0-9][0-9][0-9]$/)) ? "good" : "bad" }'

  echo "2010/04/09" | awk  -F '/' '{ print ( match($1, /^[0-9][0-9][0-9][0-9]$/) && $2 <= 04 && $3 <= 09 ) ? "good" : "bad" }'

Upvotes: 0

Related Questions