Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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

share|improve this question
    
If you're using GNU date, here is documentation on the date formats it accepts: gnu.org/software/coreutils/manual/html_node/… –  Mark Plotnick Jun 21 at 3:07

1 Answer 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
share|improve this answer
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 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 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 at 14:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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