0

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

For example, I declared an variable a and assigned an 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 "Invalid" .I want to know what is the mistake here and how to proceed.. thanks

1

The reason your test fails is because the condition test uses a value of $? that is non-zero. The reason it's non-zero is because date is producing a non-zero exit status. If you temporarily stop discarding date's stderr with the > /dev/null 2>&1 you'll get to see the error message it's producing. That will help you identify the issue.

date: invalid date ‘20150620223405’

What date is saying is that your date format is not acceptable.

You could try this:

a=20150620223405
b=$(echo "$a" | sed 's/^\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)$/\1-\2-\3 \4:\5:\6/')
c=$(date "+%Y%m%d%H%M%S" -d "$b" 2>/dev/null)
if test $? -eq 0 -a "$c" = "$a"
then
    echo ok
else
    echo not ok
fi
  • 1
    thanks.. but when I give 20152006223405(YYYYDDMMHHMISS) , instead of saying invalid it says "Valid" and displays an date in 2016 ... – Pari Sairam Mohan Jun 20 '15 at 18:27
  • Actually , the 'date' tries to convert the given date to the format specified which results in a date in 2016.So I think I must use an egrep ... – Pari Sairam Mohan Jun 20 '15 at 19:13
  • @Pari a comparison of date and the original string would pick that up; I'll modify my code shortly – roaima Jun 21 '15 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.