views:

1551

answers:

4

I want to check in linux bash whether a file was created more than x time ago.

let's say the file is called text.txt and the time is 2 hours.

 if [ what? ]
 then
     echo print "old enough"
 fi
+3  A: 

Creation time isn't stored.

What are stored are three timestamps (generally, they can be turned off on certain filesystems or by certain filesystem options):

  • Last access time
  • Last modification time
  • Last change time

a "Change" to the file is counted as permission changes, rename etc. While the modification is contents only.

Phil
+2  A: 

Consider the outcome of the tool 'stat':

  File: `infolog.txt'
  Size: 694         Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 11635578    Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/     fdr)   Gid: ( 1000/     fdr)
Access: 2009-01-01 22:04:15.000000000 -0800
Modify: 2009-01-01 22:05:05.000000000 -0800
Change: 2009-01-01 22:05:05.000000000 -0800

You can see here the three dates for Access/modify/change. There is no created date. You can only really be sure when the file contents were modified (the "modify" field) or its inode changed (the "change" field).

Examples of when both fields get updated:

"Modify" will be updated if someone concatenated extra information to the end of the file.

"Change" will be updated if someone changed permissions via chmod.

fdr
+7  A: 

Only for modification time

if test `find "text.txt" -mmin +120`
then
    echo old enough
fi

You can use -cmin for change or -amin for access time. As others pointed I don’t think you can track creation time.

kmkaplan
you can drop 'test' and the backticks. This is analogous to 'if (test == true)' vs 'if (test)'
guns
A: 

Using the stat to figure out the last modification date of the file, date to figure out the current time and a liberal use of bashisms, one can do the test that you want based on the file's last modification time (which as Phil correctly noted is not recorded).

if [ "$(( $(date +"%s") - $(stat -c "%Y" $somefile) ))" -gt "7200" ]; then
   echo "$somefile is older then 2 hours"
fi

While the code is a bit less readable then the find approach, I think its a better approach then running find to look at a file you already "found". Also, date manipulation is fun ;-)

Guss
What shell are date and stat built in to? My bash (GNU, 3.2.48) doesn't have them.
Ian Clelland
oops, sorry. `stat` is not builtin - very bad of me, I'll fix.
Guss