linuxbashfindfilesystems

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.

I don't mind having to execute the command multiple times; performance is not my primary concern for this use case, but speed would be preferable.

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.


Solution

  • I just thought of an even better solution than the previous one, which also allows me to know about deleted files.

    The idea is to use a checksum, but not a checksum of all files; rather, we can only do a checksum of the timestamps. If anything changes at all (new files, deleted files, modified files), then the checksum will change also!

    find . -type f -printf '%T@,' | cksum

    1. '%T@,' returns the modification time of each file as a unix timestamp, all on the same line.
    2. cksum calculates the checksum of the timestamps.
    3. ????
    4. Profit!!!!

    It's actually even faster than the previous solution (by ~20%), because we don't need to sort (which is one of the slowest operations). Even a checksum will be much faster, especially on such a small amount of data (22 bytes per timestamp), instead of doing a checksum on each file.