Sometimes, a developer might want to split a git commit into multiple ones. The reason for splitting a commit is typically to make the git history more readable or to reorder the commits to avoid conflicts. Luckily, this operation is possible using the reset command or an interactive rebase.
Let's get to it 😎.
The first thing to do is make sure you don't have any changes in your working directory.
This can be done using the git status command.
When running this command in the terminal, it should show no files. If it does show files, you will need to either commit the changes or discard them.
To split the most recent commit, use the
git reset command to revert the latest commit.
git reset HEAD~
HEADrefers to the current branch.
HEAD~refers to the latest commit.
Then, create different commits with the desired files and messages and push them to the remote.
But what if the commit you want to split is not the latest one?
Easy. Use interactive rebasing.
You need to rewrite the git history with an interactive rebase to split a commit farther back.
1 - First, find the commit hash with the
git reflog command.
2 - Then use the
git rebase command with the commit's hash:
git rebase -i HASH
3 - In the rebase edit screen, find the line with the commit that you want to split and replace
4 - Save and exit the rebase edit screen.
5 - Reset the state to the previous commit with:
git reset HEAD~
6 - Create different commits with the desired files and messages.
7 - Finish the rebase by typing this command:
git rebase --continue
If something goes wrong, you can abort the rebase and start over by using the
git rebase --abortcommand.
As you can see, it is easy to split a commit into multiple ones.
However, note that you will need to use the
git push --force command if you have already pushed to a remote.
Here are some other Git tutorials that I wrote for you to enjoy: