DEV Community 👩‍💻👨‍💻

Cover image for How To Split A Git Commit Into Multiple Ones?
Tim Mouskhelichvili
Tim Mouskhelichvili

Posted on

How To Split A Git Commit Into Multiple Ones?

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 😎.

git commit split

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~
Enter fullscreen mode Exit fullscreen mode

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.

interactive rebase

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
Enter fullscreen mode Exit fullscreen mode

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~
Enter fullscreen mode Exit fullscreen mode

6 - Create different commits with the desired files and messages.

7 - Finish the rebase by typing this command:

git rebase --continue
Enter fullscreen mode Exit fullscreen mode

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.

git split commit

Here are some other Git tutorials that I wrote for you to enjoy:

Top comments (1)

Collapse
 
scanepa profile image
Stefano Canepa

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.

Join us at DEV Want to join the conversation?
 

It's easy! Become a DEV member to follow this post, comment, and more.