Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to compare date and time in IF statement 1

Status
Not open for further replies.

zanzemaj

Programmer
Nov 2, 2006
35
NZ
Hi,
I need to compare the date and time in a ksh script. The date and time are contained in variables. My code generates errors which I dont know how to solve, please help.

Here is sample file named TmpFile
Code:
45e  backup              2007-05-29 02:07:32      2
46e  backup              2007-05-29 02:09:55      2
4f1  backup              2007-05-29 02:12:13      2
5ef  backup              2007-05-29 02:15:12      2

Here is my code:
Code:
StartTimeStamp="2007-05-29 02:15:12"
while read a b c d e 
    do
    a=$a
    b=$b
    c=$c
    d=$d
    e=$e
    if [ ${c} ${d} -ge ${StartTimeStamp} ] ;then 
      echo "Correct data"
    else
      echo "Incorrect data"
    fi
    done < ${TmpFile}

Here is part of the error:
Code:
+ StartTimeStamp=2007-05-29 02:15:12
+ < TmpFile
+ read a b c d e
+ a=45
+ b=backup
+ c=2007-05-25
+ d=01:39:02
+ e=2
+ [ 2007-05-25 01:39:02 -ge 2007-05-29 02:15:12 ]
process.ksh[188]: [: 01:39:02: unexpected operator/operand
+ rm -f tmp2.txt
+ read a b c d e
+ a=46e
+ b=backup
+ c=2007-05-25
+ d=02:46:05
+ e=2
+ [ 2007-05-25 02:46:05 -ge 2007-05-29 02:15:12 ]
process.ksh[188]: [: 02:46:05: unexpected operator/operand
+ rm -f tmp2.txt
 
Try quotation marks:

if [ "${c} ${d}" = "${StartTimeStamp}" ] ;then

but this is probably not what you want. But: a numerical comparison of strings (with -ge) does not make much sense.
 
Hi,

-ge -ne -eq etc are for numeric comparaison.
If you want to compare strings, you can use the C like construction.
-ge is equivalent to ( not less )
! is the operator not
< is less
use [[ boolean expression ]] instead of [ boolean expression ]

Code:
    if [red][[ ![/red] "${c} ${d}" [red]<[/red] "${StartTimeStamp}" [red]]][/red] ;then 
      echo "Correct data"
    else
      echo "Incorrect data"
    fi
 
Thank you so much yai and aau for your replies.

aau, I tried it and everything works as expected. You are brilliant! [thumbsup]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top