Splitting a commit

Sometimes we make a commit that combines changes to two separate logical units of our program, each of which should have its own commit. We can split these commits using interactive rebasing. As an example, let's split commit 26986ad into two commits. To do this we run

git rebase -i 26986ad^
Splitting a commit 1

To split a commit we use the edit option. When we close the todo file, Git will start the rebase process, but it will stop at the commit we want to rebase so that we can make our edition. At this point, we can reset and then stage and commit the changes that we want to include in one commit, and then stage and commit the changes that we want to include in the other commit.

Splitting a commit 2

Now that we've closed the file, Git started the rebase process. We see that the HEAD pointer is at commit 26986ad. We can use the reset command to go back to the state before making that commit. So we run

git reset --mixed HEAD^

and Git will move the HEAD pointer to one commit before its current position and place the changes done in the commit it's moving away from into the working directory.


Now we have two un-staged changes. We can stage and commit them one at a time.

Splitting a commit 3
Splitting a commit 4

Since neither of these commits was part of our commit tree, we have now diverged from the master branch. To continue with the rebase we run

git rebase --continue

If we now take a look at our log, we see that our tree is clean and linear. This makes maintaining our project easier.

Splitting a commit 5