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 "old enough"
fi
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 "old enough"
fi
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 time1.While the code is a bit less readable then the
find
approach, I think its a better approach then runningfind
to look at a file you already "found". Also, date manipulation is fun ;-)%Z
instead of%Y
below to get "change time" which may be what you want.[Update]
For mac users, use
stat -f "%m" $somefile
instead of the Linux specific syntax aboveI always liked using
date -r /the/file +%s
to find its age.You can also do
touch --date '2015-10-10 9:55' /tmp/file
to get extremely fine-grained time on an arbitrary date/time.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):
a "Change" to the file is counted as permission changes, rename etc. While the modification is contents only.
The find one is good but I think you can use anotherway, especially if you need to now how many seconds is the file old
date -d "now - $( stat -c "%Y" $filename ) seconds" +%s
using GNU date
Only for modification time
Or, the same in one line:
You can use
-cmin
for change or-amin
for access time. As others pointed I don’t think you can track creation time.Although ctime isn't technically the time of creation, it quite often is.
Since ctime it isn't affected by changes to the contents of the file, it's usually only updated when the file is created. And yes - I can hear you all screaming - it's also updated if you change the access permissions or ownership... but generally that's something that's done once, usually at the same time you put the file there.
Personally I always use mtime for everything, and I imagine that is what you want. But anyway... here's a rehash of Guss's "unattractive" bash, in an easy to use function.