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 π.
Preparation
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.
How to split the most recent commit?
To split the most recent commit, use the git reset
command to revert the latest commit.
git reset HEAD~
HEAD
refers 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.
How to split a commit farther back?
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 pick
with edit
.
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 --abort
command.
Conclusion
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:
Top comments (2)
The instructions for splitting commits farther back in the history are incorrect. Your step two should read
git rebase -i HASH~1
or else the commit you want to split will not be included; just all commits after it.
In same cases creating a new branch from mainline and checking out from the big branch to the new branch only the file you need is the easiest way.