January 15th, 2012

Reconstructing directory modification times

I’m currently migrating large parts of a Windows NTFS partition to Ext4 on my desktop system and accidentally messed the modification times of all directories I moved with Dolphin (KDE) by aborting the operation and restarting it over the already created directories from the first run. I decided to hack a small script to reconstruct the modification times (getting close to the original ones). It works by recursively finding the latest, deepest nested file modification time for a directory (as those have been copied correctly) and using touch to set the same timestamp on the target directory. I would advise to call it with find on the directories it should operate on, for example if it has been saved as ~/fix-copied-dirtimes.sh:

find first/ second/ -type d -not -empty -exec ~/fix-copied-dirtimes.sh \{\} \;

It is by far not optimized (being called this way will perform highly redundant queries on the file system) but it works very fast nevertheless and you usually don’t run it frequently, so that’s okay…

A little word of warning: Verify the correct behaviour on your own! That means: Please manually confirm that all calls performed by this script and method turn up with the correct result. This comes without any warranty and although touch shouldn’t do any more than changing timestamps you never know… ;) So… do your checks please and try it on some unimportant test directories first.

# sets one directory modification time according to its latest file modification time (searched recursively)

LATESTDATE=`find "$DIR" -type f -printf '%TY%Tm%Td%TH%TM.%TS\n' | sort -n | tail -n1 | cut -c-15`

        touch -m -t "$LATESTDATE" "$DIR"

Comments are closed.