Search code examples
comparisontcshstat

tcsh & stat: comparing files' modification times in script


I wrote a tcsh script [warning, I am fairly new to tcsh!] that checks the extension of the input file, if it has read permissions, and also outputs a pdf version from its .tex input file.

My next step is wanting to make the program exit if the modification time of the generated, pdf, file is more recent than the input file's modification time.

I saw that I could resort to stat and thought of storing the modification times from stat into variables.

#$1 is the name of the .tex file, like sample.tex
set mtime_pdf = `echo stat -c %Y $1:t:r.pdf` 
set mtime_tex = `echo stat -C %Y $1`

Now how do I go about comparing them? I want to be able to do something like (this is more pseudo-code like)

if ( $mtime_pdf < $mtime_tex ) then
      echo "too new!"
      exit 2

Thoughts? Thank you!


Solution

  • You didn't say but stat -c %Y points towards Linux. The problem with stat is that its arguments aren't very portable. A more portable way of doing file compares is using find.

    Your set commands should lose the echo.

    All in all here is an example that demonstrates both approaches:

    #!/usr/bin/tcsh
    
    if ( $#argv < 2 ) then
        echo "Usage: $0 <file> <file>"
        exit 2
    endif
    
    set t1=`stat -c '%Y' $1`
    set t2=`stat -c '%Y' $2`
    echo "$1 is $t1 seconds old"
    echo "$2 is $t2 seconds old"
    
    if ( $t1 < $t2 ) then
        echo "$1 is older as $2"
    else
        echo "$1 is newer or the same age as $2"
    endif
    
    if { find $1 -newer $2 } then
        echo "$1 was modified after or at the same time as $2"
    else
        echo "$1 was modified before as $2"
    endif
    
    if { find $1 -cnewer $2 } then
        echo "$1 was created after or at the same time as $2"
    else
        echo "$1 was created before $2"
    endif