How to verify that file2 is newer than file1 in bash?

How can I verify that file2 was last modified after file1?

In this example, perl was modified more recently than stack. Is there a bash or Linux command that can compare these files based on the modification time?

-rw-r--r--    1 root     root         1577 Sep  7 22:55 stack
-rwxr-xr-x    1 root     root          626 Sep  7 23:10 perl

Solution 1:

Found it here

for f in /abcd/xyz* do
   [ "$f" -nt /abcd/test.txt ] && echo "file f$ found" done

Solution 2:

if [[ FILE1 -nt FILE2 ]]; then
  echo FILE1 is newer than FILE2
fi

Taken from 'man test'. Excerpt:

FILE1 -nt FILE2
  FILE1 is newer (modification date) than FILE2

Solution 3:

Another way to do this:

find -name file2 -newer file1

will return null if file2 is older or the same age as file1. It will return the name (and directory) of file2 if it's newer.

Be aware that Linux doesn't keep track of when files were created. These tests will be for the most recent modification date and time.

Solution 4:

If you want more detailed information you can use the stat command

<tbielawa>@(fridge)[~/SuperUser] 03:15:10
$ touch firstFile
<tbielawa>@(fridge)[~/SuperUser] 03:15:24
$ touch secondFile
<tbielawa>@(fridge)[~/SuperUser] 03:15:45
$ stat firstFile 
  File: `firstFile'
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: 805h/2053d  Inode: 151528      Links: 1
Access: (0644/-rw-r--r--)  Uid: (  500/tbielawa)   Gid: (  500/tbielawa)
Access: 2010-09-14 03:15:24.938721003 -0400
Modify: 2010-09-14 03:15:24.938721003 -0400
Change: 2010-09-14 03:15:24.938721003 -0400
<tbielawa>@(fridge)[~/SuperUser] 03:15:48
$ stat secondFile 
  File: `secondFile'
  Size: 0           Blocks: 0          IO Block: 4096   regular empty file
Device: 805h/2053d  Inode: 151529      Links: 1
Access: (0644/-rw-r--r--)  Uid: (  500/tbielawa)   Gid: (  500/tbielawa)
Access: 2010-09-14 03:15:45.074722792 -0400
Modify: 2010-09-14 03:15:45.074722792 -0400
Change: 2010-09-14 03:15:45.074722792 -0400

Solution 5:

echo $(($(date -r file1 +%s)-$(date -r file2 +%s)))
2208

If the result is > 0, the first file is newer. (Newer in terms of last modification-, not creation-time, which is stored on linux).