DEV Community

Espoir Murhabazi
Espoir Murhabazi

Posted on • Updated on

How to count the number of commits made between 2 commits hashes

The problem

You have been working hard on that feature for many days and now it's done.
Unfortunately, you have made a lot commit and you want to squash them into one commit and raise that pull request.

As said in this tutorial you can do it in one command :

git rebase -i HEAD~[NUMBER OF COMMITS]

But How to know the number of commits you have made since the moment you started working on this feature?

The solution

With git log you can list all the commit you made after creating your branch.

Let suppose your first commit hash is 33b14c62b and the last commit hash is 33ad6cecf

You can do it the old way by counting manually the number of commits between the two hashes but it is not always easy.

Git has a powerful command called rev-list that lists commit objects in reverse chronological order

git rev-list 33b14c62b...33ad6cecf

With that command, you can get the list of all commit between the start hash and the end hash.

To count the number of line in the output of that command use the pipe and the following command: | wc -l.

The final command will look like this :

git rev-list 33b14c62b...33ad6cecf | wc -l

Putting all together!

Once you get the number of commits you would like to squash you can do the command mentioned in the introduction and combine your commit by deciding what you would like to pick and what you would like to squash.
If you have found 10 commits the command will be :

git rebase -i HEAD~10

All In One:

You can combine all the 2 commands into one command and remove white spaces and tabs using this:

git rebase -i HEAD~"$(git rev-list 33b14c62b...33ad6cecf | wc -l | sed 's/ //g')"

Special thanks to @paesibassi for this suggestion

Regards.

Resources used :

An answer on stackoverflow

git rev-list from the git bible

Top comments (4)

Collapse
 
paesibassi profile image
Federico Calore • Edited

You can pass the output of the wc command to sed to remove the any whitespace.
This should work:

git rebase -i HEAD~"$(git rev-list 33b14c62b...33ad6cecf | wc -l | sed 's/ //g')"

Collapse
 
espoir profile image
Espoir Murhabazi

Thanks for this input dear Federico,
Let me try to edit the post

Collapse
 
andy profile image
Andy Zhao (he/him)

Nice post Espoir! Not sure how to combine the two commands into one, but I think it's nice to have it as two commands as well.

Collapse
 
drmahikbov profile image
drmahikbov

Hi thanks really helpful. Could you please show how to make a git alias from this please It would be extremely helpful