Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readGit

Find the last commit for each file

Use git last-modified to find the latest commit for each file in a directory, at HEAD or in an older committed tree.

You need a last-changed commit beside each file in src/. A plain git log -- src gives you a history of the directory, so you have to work out which commit belongs to each file.

Git 2.52 added git last-modified to answer that per path. It prints a commit ID and a path for each result.

Ask for files under a directory

Run these commands from the repository root.

git last-modified -- src
git last-modified -r -- src

The first call shows a row for src. The recursive call shows rows for files under it and omits the directory row.

In a small repository where the second commit changed src/config.js, the recursive command returned:

b23e4751dfdbab67fc3045b20b0352525cd41dd1	src/config.js
c017e9e2f515400f4023460e440872fbac1454da	src/lib/version.js

The config points to the second commit, and the version file still points to the first.

Git walks committed history. Editing either file in your working tree leaves those rows as they were. Git also counts certain changes that leave the file contents intact, such as changing a file's executable bit. If the report must track edits to the text itself, inspect the returned commit before treating its timestamp as the date the text changed.

Check an older tree

With no revision, Git starts at HEAD. Give it an older commit to ask the same question as of that tree.

git last-modified -r HEAD^ -- src

In the two-commit repository, both files now point to the first commit.

Keep the revision before -- and the path after it. The separator helps when a ref and a file or directory have the same name. A file absent from that older tree has no row there.

For a human report, use each returned hash to look up the commit date with git show -s --format=%cs <hash>. Leave the full hash in any saved output so you can check the exact commit later. For scripts, use -z with Git 2.54 or later. The last-modified manual specifies a NUL after each raw pathname. Split each record at its first tab to preserve tabs in the filename.