DEV Community

Cover image for Split an existing git commit
Hugo Di Francesco
Hugo Di Francesco

Posted on • Originally published at on

Split an existing git commit

One of git's main differences when compared to other version control systems is that it lets the user rewrite the history. The main way to do this is to use git rebase, usually followed by a git push --force to overwrite history the remote with the local history.

Here’s a look at how to split existing commits using rebase, reset and commit.

Say you have two files edited in a commit (A and B) and you would like to get the changes from one of those files (A) into your current branch but not those from the other (B).

Using git cherry-pick <commit-hash> is not an option since it would pull in the changes for both A and B.

The solution is to split the commit into 2 and only cherry-pick the new commit that contains changes for A.

To do this:

  • run git rebase -i <commit-hash>~ (note the ~) or git rebase -i <hash-of-previous-commit>
  • find the commit you want to split in the rebase edit screen, change the pick to e (edit)
  • save and exit (ESC followed by :wq to close VIM)
  • git reset HEAD~ to reset the staged changes
  • git add [files-to-add] all the files we want to add to the first commit (here would be git add A)
  • git commit normally, with a message etc
  • Run as many other rounds of as you want commits:
    • git add [other-files-to-add]
    • git commit
  • git rebase --continue to indicate that the splitting has been finished and to continue the rebase

Finally we can git cherry-pick <new-commit-hash> to get the changes into our branch

For any questions about using git, feel free to comment below or tweet to me @hugo__df.

Subscribe to get the latest posts right in your inbox (before anyone else).

Cover photo by Markus Spiske on Unsplash

Top comments (3)

hoelzro profile image
Rob Hoelz

FWIW, you can use git cherry-pick -n $COMMIT to pull in a commit's changes into your index without pulling in the commit itself!

colinmtech profile image
Colin Morgan

git add --patch <filename> is also really useful if you only want to commit a subset of your changes to a file.

Git has all kinds of cool commands that aren't mentioned often.

ben profile image
Ben Halpern

I need to make a habit of doing this when it’s needed.