Git commits in date order

Given a repository with two commits, the second one has a date from before the first:

git log
commit 7dc52d6ca1dc54ad33c52dea873328d46939e9f4
Author: Bob <bob@example.com>
Date:   Thu Mar 2 06:26:56 2023 +0100

    Update file.txt

commit 75bb369d099d0e4fd136e67ff3ef638552790fae
Author: Alice <alice@example.com>
Date:   Thu Mar 2 09:09:56 2023 +0100

    Add file.txt

In some situations—like finding the last commit that touched a file—we need the log to be in date order, meaning the commits should be reversed in the log output.

Git provides the --author-date-order flag, but that still shows all parents before their children. Since the first commit is the parent of the second, the order remains the same:

git log --author-date-order
commit 7dc52d6ca1dc54ad33c52dea873328d46939e9f4
Author: Bob <bob@example.com>
Date:   Thu Mar 2 06:26:56 2023 +0100

    Update file.txt

commit 75bb369d099d0e4fd136e67ff3ef638552790fae
Author: Alice <alice@example.com>
Date:   Thu Mar 2 09:09:56 2023 +0100

    Add file.txt

The way I found go get the commits in date order is by stringing three commands together:

git log --format="%ad %H" --date=format:%s
Return the log for the repository, with %ad %H as the format (the author date and commit hash) and %s as the date format (a timestamp)1.
sort --reverse
Sorting the list in reverse chronological order, based on the timestamps.
awk '{ print $2 }'
Use awk to get the second column from each line, which is the commit hash.
git log --format="%ad %H" --date=format:%s | sort --reverse | awk '{ print $2 }'
75bb369d099d0e4fd136e67ff3ef638552790fae
7dc52d6ca1dc54ad33c52dea873328d46939e9f4

Now we know the exact date order of the commits in the repository.

With the list of commits in the right order, we can even call git show for each line to get something that resembles a log:

git log --format="%ad %H" --date=format:%s | sort --reverse | awk '{ system("git show --quiet " $2); print("\n") }'
commit 75bb369d099d0e4fd136e67ff3ef638552790fae
Author: Alice <alice@example.com>
Date:   Thu Mar 2 09:09:56 2023 +0100

    Add file.txt


commit 7dc52d6ca1dc54ad33c52dea873328d46939e9f4
Author: Bob <bob@example.com>
Date:   Thu Mar 2 06:26:56 2023 +0100

    Update file.txt



  1. :

    The intermediate format looks like this:

    git log --format="%ad %H" --date=format:%s
    
    1677734816 7dc52d6ca1dc54ad33c52dea873328d46939e9f4
    1677744596 75bb369d099d0e4fd136e67ff3ef638552790fae
    
    ↩︎