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.
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:
That's a wrap. I hope you found this article helpful and you learned something new.
As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.
If you'd like to receive future articles directly in your email, please subscribe to my blog. Your email is respected, never shared, rented, sold or spammed. If you're already a subscriber, thank you.