Comparing modified times of files

Steven M. List itkin at mrspoc.Transact.COM
Tue Mar 12 04:33:38 AEST 1991


scottp at bwdlh504.bnr.ca (Scott Pace) writes:

>I would like to be able to compare two files' time stamps, to see which one
>is the oldest (or newest). How can I do this with sh?
>I know about ksh and perl, but I want to know how it can be done with plain
>old Bourne Shell.
>I am running on HP-UX, if that makes a difference.

A simple way is to use find:

    find file1 -newer file2 -print

If file1 is newer than file2, then the name of "file1" will be printed
on stdout.  If not, then the output will be empty.  Unfortunately, in 
both cases the status value is 0, so you can't check for success or
failure.

If you're interested in something a bit faster that can also handle a
LIST of files, I wrote a little program a few years back that does
a few things:

    -   compares the last modification times of the files on the command
        line
    -   exits with the ordinal of the newest file as the status code
    -   prints the name of the newest file on standard output

So, just on the off-chance that someone can use it, here it is:
-----------CUT HERE-----------------------------------------------------------
#include    <sys/types.h>
#include    <sys/stat.h>
#include    <stdio.h>

struct stat sb, sbt;

int     max = 0;

char    *pgm;

main (ac, av)
int     ac;
char    *av[];
{
    register int i;

    register int error = 0;

    char    *strrchr ();

    sb.st_mtime = sbt.st_mtime = sb.st_ctime = sbt.st_ctime = 0;

    for (i = 1; i < ac; i++)
    {
        if (stat (av[i], &sbt) == 0)
        {
            if (sbt.st_mtime > sb.st_mtime || sbt.st_ctime > sb.st_ctime)
            {
                sb = sbt;
                max = i;
            }
        }
    }

    printf ("%s\n", av[max]);

    exit (max);
}
-----------CUT HERE-----------------------------------------------------------
No big deal, right?  But useful at times.
-- 
 +----------------------------------------------------------------------------+
 :                Steven List @ Transact Software, Inc. :^>~                  :
 :           Chairman, Unify User Group of Northern California                :
 :                         itkin at Transact.COM                                 :



More information about the Comp.unix.shell mailing list