Write Software, Well

How to Count the Number of Commits After a Specific Commit in Git

August 25, 2024

I often like to squash multiple commits together into a single commit. For this, I tend to use the git reset --soft HEAD~n command frequently, where n is the number of commits I'd like to cherrypick.

💡 Update: Ben pointed out in the comments that if you know which commit you want to reset to, you can simply do: git reset --soft <commit-id> instead of HEAD~n. Not sure why I never thought of this 🤦‍♂️. That said, the rest of the post is still valid to count the number of commits after a commit.

For a small number of commits, it's easy to just count the number of commits manually. However, often I have a long list of commits and counting them all can be tedious. To address this, I was looking for a command that would give me the number of commits made after a specific commit, and came across rev-list, combined with the count flag.

To count the number of commits made after a specific commit in Git, you can use the following command:

git rev-list <specific_commit>..HEAD --count

Here’s a breakdown of the command:

  • git rev-list: Lists commit objects in reverse chronological order.
  • <specific_commit>: Replace this with the hash of the commit you are interested in.
  • ..HEAD: This specifies the range from the specific commit to the latest commit (HEAD).
  • --count: Outputs the number of commits instead of the commit hashes.

For example, if your specific commit hash is abc123, the command would be:

git rev-list abc123..HEAD --count

This will give you the number of commits made after the specified commit up to the latest commit. Now you can plug in this number in the git reset --soft HEAD~n to squash them together (or write a shell script that does this in a single command).

If you're using VS Code with the GitLens extension, you can easily copy the commit SHA, as shown below:

copy_git_sha.png
Copy Git SHA VS Code