Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the timestamp of the latest modified file in a directory (recursively)?

I'm working on a process that needs to be restarted upon any change to any file in a specified directory, recursively.

I want to avoid using anything heavy, like inotify. I don't need to know which files were updated, but rather only whether or not files were updated at all. Moreover, I don't need to be notified of every change, but rather only to know if any changes have happened at a specific interval, dynamically determined by the process.

There has to be a way to do this with a fairly simple bash command. I don't mind having to execute the command multiple times; performance is not my primary concern for this use case. However, it would be preferable for the command to be as fast as possible.

The only output I need is the timestamp of the last change, so I can compare it to the timestamp that I have stored in memory.

I'm also open to better solutions.

like image 310
Marco Roy Avatar asked Jun 20 '15 23:06

Marco Roy


People also ask

How do I find the latest modified file in Linux?

You can use the ls command to list files including their modification date by adding the -lt flag as shown in the example below. The flag -l is used to format the output as a log. The flag -t is used to list last modified files, newer first.

How do I get the latest timestamp of a file in Unix?

%T@ returns the modification time as a unix timestamp, which is just what I need. sort -n sorts the timestamps numerically. tail -1 only keeps the last/highest timestamp.

How do I find recently modified files?

How to find the date of modified files. Press the Windows key + E on the keyboard to open File Explorer. On the left side-scrolling menu, select the drive or folder that you want to view the last modified date(s) (A) for the contents.


1 Answers

I actually found a good answer from another closely related question.

I've only modified the command a little to adapt it to my needs:

find . -type f -printf '%T@\n' | sort -n | tail -1

  1. %T@ returns the modification time as a unix timestamp, which is just what I need.
  2. sort -n sorts the timestamps numerically.
  3. tail -1 only keeps the last/highest timestamp.

It runs fairly quickly; ~400ms on my entire home directory, and ~30ms on the intended directory (measured using time [command]).

like image 140
Marco Roy Avatar answered Sep 19 '22 18:09

Marco Roy