Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 comparision is not working, I guess. Or if there is any other nice way than what I am doing, please let me know.

Thanks

Edit: Solved. There was no space in between if, so changing it to this works:

if [ $file1time -gt $file2time ] 
share|improve this question
1  
Your code needs spaces around the square brackets. –  Jonathan Leffler May 6 '10 at 15:02
    
The test mechanism is very complex compared with the built in mechanism for comparing time stamps. –  Jonathan Leffler May 6 '10 at 15:03
add comment

4 Answers

The operators for comparing time stamps are:

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

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

share|improve this answer
add comment

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 ];
share|improve this answer
2  
[ is a test command -- see the "CONDITIONAL EXPRESSIONS" section of the bash man page. There's also a standalone executable in /usr/bin/test and /usr/bin/[, but if you're using bash and not using the full path, yo u're using the shell builtin. –  Doug Harris May 6 '10 at 13:11
    
@Doug Harris +1 for the more complete explanation about the topic. –  goedson May 6 '10 at 13:18
add comment

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" ]
share|improve this answer
add comment
if ( [ $file1time -gt $file2time ] );
then
 doSomething
fi                                                                    
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.