Determine if a file has been modified

filesstattimestamps

In Linux (currently using ext4 filesystem), how can one check quickly if the contents of a file has been modified without reading any of its contents?

Is the stat command a recommended approach? I currently do

$ stat --format "%Y" hello.txt

and later I can check if the same command yields the same output. If it does, I conclude that hello.txt has not changed.

My feeling is that one wants to throw in more parameters to be even more sure. For example, would adding the file size, file name, etc, provide an even better "fingerprint" of the file?

On this topic, I recall that a TrueCrypt volume I once had was always ignored by my incremental backup program, possibly because TrueCrypt made sure to leave no meta data changes behind. I suppose it is indeed possible to change all the data returned by stat, hence it cannot be guaranteed to pick up on every possible modification of the file?

Best Answer

If you want to detect whether a file has been modified through normal means (editing it in some application, checking out a new version from a revision control systems, rebuilding it, etc.), check whether its modification time (mtime) has changed from the last check. That's what stat -c %Y reports.

The modification time can be set by the touch command. If you want to detect whether the file has changed in any way (including the use of touch, extracting an archive, etc.), check whether its inode change time (ctime) has changed from the last check. That's what stat -c %Z reports. The ctime cannot be spoofed except by the system administrator (and even then, only through indirect means: by changing the system clock, or by accessing the disk directly, bypassing the filesystem).