Restoring file mtimes with git

📄 BetterWays.dev wiki page | 🕑 Last updated: Jan 22, 2022

Sometimes is useful to restore the modification times from their last commits - i.e. you're creating a tarball, building a static site which depends on mtimes, etc.

Great news is that there's a part of git-tools which does exactly that. It's very like that you have it in your distro repos (i.e. apt install git-restore-mtime on Debian/Ubuntu).
Now you just need to go into the repository and run it there:

cd my-repo
git restore-mtime

If you can't (or don't want) to install additional packages, you can try something like this:

for f in $(git ls-tree -r -t --name-only --full-name) ; do
    touch -d $(git log --pretty=format:%cI -- "$f") "$f";
done

(we're listing files with git ls-tree, then calling touch -d with the formatted result of git log on every file)


Comments and suggestions

You can use this form to submit a suggestion or a comment.

If you find this site useful, please consider supporting it. Supporters also get access to some extras.