Marek
Marek

Reputation: 133

Why is my string comparison in Bash always evaluated as true?

I have a script checking if a file is up-to-minute.

updatedate=`ls -l file | sed -e 's/  */ /g' | cut -d' ' -f7` #cut the modification time
nowdate=`date +"%H:%M"`
echo "$updatedate $nowdate"
if [ "$updatedate"="$nowdate" ]
then
  echo 'OK'
else
  echo 'NOT OK'
fi

But when I run it, the comparison is always true:

$ ./checkfile
10:04 10:07
OK

$ ./checkfile
10:07 10:07
OK

Why?

Upvotes: 8

Views: 3815

Answers (2)

CB Bailey
CB Bailey

Reputation: 791719

You need to separate all the arguments to test with whitespace. As it stands you have = right up against its two operands so test sees one argument, not the three that you intend.

Upvotes: 2

jcomeau_ictx
jcomeau_ictx

Reputation: 38422

You need a space on each side of the equals sign.


if [ "$updatedate" = "$nowdate" ]

Upvotes: 19

Related Questions