matsientst
matsientst

Reputation: 620

Comparing two date strings in bash

I am having trouble with a script that checks the date of a table to make sure the slave's data is up to date

The problem is that the date equality is coming back incorrect:

NOW=$(date +"%Y-%m-%d")
VALUE=`mysql -uroot -p database -e "select DATE_FORMAT(create_date,'%Y-%m-%d') as '' from actions order by id desc limit 1"`
echo $NOW $VALUE
if [ "$?" -ne 0 ]; then
   MSG="MySQL check data date failed"
   echo $MSG
   echo $MSG > $MESSAGE
   /bin/mail -s "$SUBJECT" "$EMAIL" < $MESSAGE
   exit 7
fi
if [ "$NOW" != "$VALUE" ]; then
   echo "not equal"
fi

The output is that they are not equal:

2011-12-08 2011-12-08
not equal

My guess is that I am comparing two different types, but according the bash documentation that shouldn't be the case. Can someone explain this to me? Thanks

Upvotes: 2

Views: 2602

Answers (1)

shellter
shellter

Reputation: 37318

If you turn on the shell debugging set -vx, you'll see each line (or block of code like while, for loops) displayed, (verbose mode), then you get the line as it being executed with all variables expanded to their current values. Change the last conditional to

if [ "X${NOW}X" != "X${VALUE}X" ] ; then ....

And you can easily tell if $NOW or $VALUE have any extra while-space characters embedded. Once you can see where the differences are, then you can easily determine how to fix the assignment of those values.

I hope this helps.

Upvotes: 4

Related Questions