Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

bash

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?

like image 943
Marek Avatar asked May 14 '11 08:05

Marek


2 Answers

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


if [ "$updatedate" = "$nowdate" ]
like image 85
jcomeau_ictx Avatar answered Sep 28 '22 04:09

jcomeau_ictx


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.

like image 42
CB Bailey Avatar answered Sep 28 '22 02:09

CB Bailey