24

How do I compare the timestamp of two files?

I tried this but it doesn't work:

file1time=`stat -c %Y fil1.txt`
file2time=`stat -c %Y file2.txt`
if[$file1time -gt $file2time];
then
 doSomething
fi

I printed both the time stamps, in order and it gives me

1273143480
1254144394
./script.sh: line 13: [1273143480: command not found

So basically if comparison is not working, I guess. Or if there is any other nice way than what I am doing, please let me know. What do I have to change?

Jens Erat
  • 18,485
  • 14
  • 68
  • 80
newcoderintown
  • 349
  • 1
  • 2
  • 4

4 Answers4

44

The operators for comparing time stamps are:

[ $file1 -nt $file2 ]
[ $file1 -ot $file2 ]

The mnemonic is easy: 'newer than' and 'older than'.

7

This is because of some missing spaces. [ is a command, so it must have spaces around it and the ] is an special parameter to tell it where its comand line ends. So, your test line should look like:

if [ $file1time -gt $file2time ];
goedson
  • 946
2

if is not magic. It attempts to run the command passed to it, and checks if it has a zero exit status. It also doesn't handle non-existent arguments well, which is why you should quote variables being used in it.

if [ "$file1time" -gt "$file2time" ]
0
if ( [ $file1time -gt $file2time ] );
then
 doSomething
fi                                                                    
Renju Chandran chingath
  • 1,473
  • 3
  • 12
  • 19