0

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

2
  • what are you trying to achieve. Commented Sep 30, 2016 at 10:47
  • I want to check whether input date is in yyyy-mm-dd format. Commented Sep 30, 2016 at 11:00

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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" }'

Comments

0

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

1 Comment

$? is a special variable. It stores the exit status of last command. If last command runs successfully then it will be 0 and other value if not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.