git rebase - Combine few commits into one commit

Let’s assume that we have a commit history like below in our project.

Note that the master branch is pointed to commit 5af0ee, dev branch is pointed to commit e0e165 and HEAD is pointed to dev branch.

We have feature 1, feature 2 in master branch and feature 3 in dev branch, in dev branch feature 3 consists of 4 minor commits and we want to combine all feature 3 commits to a single commit.

basically we want to combine these 4 commits having all feature 3 changes e0e165fd9f06c55d0f1419257aa03fb567b3c0ba, 3492b6a4e5bc530185346c5af8f613a9b3c1ca6c, 3c6de8a9ea1d31a23126c22c86d5a497877f272e, 7bd4d6dbdf8aea4257311327fb8bf37511fdefe3

We’ll use git rebase interactive mode as below command, -i means interactive.

Let’s say we want the combined commit to come after feature 2 commit 7fa647325840f50c3f263429e5315ffd48d244ca

this command will open vim text editor as below, in my case i’m using mac and it opened vim editor, note that the oldest commit top and latest commits after, all the lines starts with # are comments.

To combine the commits together we’ll use squash.

(if the terminal editor is vim, press i on mac or press insert button on windows to edit the text)

After setting squash it’ll be as below, the starting commit is kept as pick, all other commits to combine with the feature 3 starting commit is changed to squash.

Press Esc key and type :wq to save the changes (standard vim editor features).

After save the terminal will show following text, lines staring # are all comments.

We can use # to comment out all previous commit messages and add a new commit message for the combined commits ex. Feature 3.

Press Esc key and type :wq to save the changes (standard vim editor features).

After combining the commits the git log will show as below.

references:

https://www.internalpointers.com/post/squash-commits-into-one-git

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store