Tech Note
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

The Easiest Way to Get The Number of Git Commits to Squash

Let’s say you’re working on the Jira task ABC-123. You’ve finished the coding and you’re ready to create a merge request. You’d like to squash the commits in your branch so that your merge is relatively tidy.

You need to know how many commits you’ve made in your branch. Luckily for you, you’ve developed a habit of putting the Jira ticket ID as the prefix for each commit line, so you can just count the number of commits that have the prefix ABC-123.

Now, you can easily do a git rebase -i HEAD..<some-number> and just squash the commits that have the prefix. Or count the commits that appear in git log ABC-123. But probably the easiest way is to use the shell to do the counting for you.

Here’s the easiest way to get the number of commits is by running te following:

git log | grep ABC-123 | wc -l

You can then use that number in your git rebase -i HEAD..n command. Or if you’re feeling adventurous, you can merge the two into a single command that counts and squashes at the same time.

git rebase -i HEAD.."`git log | grep ABC-123 | wc -l | sed -e 's/ //g'`"

The use of sed here is to remove the spaces that appear in wc’s output.

(this was originally a blog post)