Path: utzoo!attcan!uunet!mcsun!ukc!acorn!ixi!mike From: mike@x.co.uk (Mike Moore) Newsgroups: comp.unix.questions Subject: Re: how to compare file modification time in bourne shell script Message-ID: Date: 26 Jul 90 10:27:45 GMT References: <1990Jul23.233044.2729@silma.com> <840@ehviea.ine.philips.nl> Reply-To: mike@x.co.uk (Mike Moore) Organization: IXI Limited, Cambridge, UK Lines: 65 In article <1990Jul23.233044.2729@silma.com> aab@silma.UUCP () writes: > >I need to compare the modification times of two files in a bourne shell >script. I would like to do this without writing C code. >Machine is Sparcstation 1 running SunOS 4.03c > >Thus I need a function: > >newer file1 file2 > >that returns 0 if file1 is newer than file2 else returns 1 > >Can it be done? Here is a way: newer() { file=$1 set `ls -t $1 $2` # func args are now changed [ $file = $1 ] && return 0 || return 1 } For those that don't know, the second line is an alternative form of: if [ $file = $1 ] then return 0 else return 1 fi Of course, file1 and file2 have to exist, and have to be files. If you don't want to use set, then: [ `ls -tC $1 $2 | sed 's/ .*$//'` = $1 ] && return 0 || return 1 And to do the whole thing properly: newer() { file=$1 [ ! -f $1 -o ! -f $2 ] && return 2 # error exit set `ls -dt $1 $2` # func args are changed [ $file = $1 ] && return 0 || return 1 } Now file1 and file2 don't have to exist and don't have to be files. Line #2 in this final version could be changed to two seperate lines: [ ! -f $1 ] && return 1 # since file2 is newer [ ! -f $2 ] && return 0 # since file1 is newer if you want a different effect. Using this method, then, on most machines, the only program actually read from disk and executed is ls (some may actually execute the '['). Happy Bourne Shell! Mike -- -------------------------------------------------------------------------- Usual disclaimer..... etc | mike@x.co.uk True Intelligence is not knowing all the answers, | it's knowing the right questions. |