How to compare two strings

Hi all,

I am trying to compare two strings/dates, but its throwing error::Syntax error at line 5:

Please help !!

Any alternate way to compare two dates is also fine....
logdate1=`date -u '+%Y.%m.%d %T'`
sleep 5
logdate2=`date -u '+%Y.%m.%d %T'`
if test $logdate1 -ge $logdate2
then
echo "$logdate1 is greater"
else
echo "$logdate2 is lesset"
fi

Regards
Prashant

Insert

"set -x" at the beginning of your script and run it.

Then look at the contents of your logdate1 and logdate2 variables.

I don't think that it wil be able to cope with periods and spaces within the string variables.

Good luck

Mika

###

Since u r comparing two string use '$var' .
Agn in ur prog u used 2 str to comp which gv the wrong result
There r many ways 2 solve this ..I hv written as given below..
Plz chk...:slight_smile:

==============================================
logdate1=`date -u '+%Y.%m.%d %T'`
sleep 5
logdate2=`date -u '+%Y.%m.%d %T'`

d1=`echo $logdate1 | tr '.' ':' | tr ':' ' ' `
d2=`echo $logdate2 | tr '.' ':' | tr ':' ' ' `
dt1=''
dt2=''
for d in $d1
do
dt1=$dt1$d
done
for d in $d2
do
dt2=$dt2$d
done
if [ ` expr $dt1 ` -ge ` expr $dt2 ` ];then
echo "logdate1=$logdate1 is greater"
else
echo "logdate2=$logdate2 is greater"
fi

You are making it too hard on yourself. Use

date +%s

Which gives you the time in seconds.

If you need to get the greater/lesser of the date strings, you can instead use the date command as you have it, pipe it through sort, and then use tail -1 (greater) or head -1 (lesser).

{ date -u '+%Y.%m.%d %T'; sleep 1; date -u '+%Y.%m.%d %T'; } |sort | head -1

:b:That is good but I used the way how Prashant tried.. so tht he can find wht is the prob in his string comp approach..

The problem is that he's comparing a string using the shell's NUMERICAL comparators (lt, ge, etc). He could use bash's STRING comparators. The weird thing is that they have to be escaped, so I avoid them.

$ test "0.1.2" \< "0.1.3" && echo smaller
smaller

Again, that only works in BASH (at least since version 2.05 // 2005).