Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break a previous commit into multiple commits

Tags:

git

Without creating a branch and doing a bunch of funky work on a new branch, is it possible to break a single commit into a few different commits after it's been committed to the local repository?

like image 225
koblas Avatar asked Jun 02 '11 16:06

koblas


People also ask

How do I abandon a previous commit?

Undo Last Git Commit with reset. The easiest way to undo the last Git commit is to execute the “git reset” command with the “–soft” option that will preserve changes done to your files. You have to specify the commit to undo which is “HEAD~1” in this case. The last commit will be removed from your Git history.

How do I roll back multiple commits?

To revert multiple commits in the middle of the history, use an interactive rebase. Find the last commit's hash containing all the commits you want to remove. Start an interactive rebase session with git rebase -i <hash>. In the interactive rebase edit screen, remove the commit lines you want to remove.

Can I edit a previous commit?

The git commit --amend command is a convenient way to modify the most recent commit. It lets you combine staged changes with the previous commit instead of creating an entirely new commit. It can also be used to simply edit the previous commit message without changing its snapshot.


1 Answers

git rebase -i will do it.

First, start with a clean working directory: git status should show no pending modifications, deletions, or additions.

Now, you have to decide which commit(s) you want to split.

A) Splitting the most recent commit

To split apart your most recent commit, first:

$ git reset HEAD~ 

Now commit the pieces individually in the usual way, producing as many commits as you need.

B) Splitting a commit farther back

This requires rebasing, that is, rewriting history. To specify the correct commit, you have several choices:

  • If it is three commits back, then

      $ git rebase -i HEAD~3 

    where 3 is how many commits back it is.

  • If it is farther back in the tree than you want to count, then

      $ git rebase -i 123abcd~ 

    where 123abcd is the SHA1 of the commit you want to split up.

  • If you are on a different branch (e.g., a feature branch) that you want to merge into master:

      $ git rebase -i master 

When you get the rebase edit screen, find the commit you want to break apart. At the beginning of that line, replace pick with edit (e for short). Save the buffer and exit. Rebase will now stop just after the commit you want to edit. Then:

$ git reset HEAD~ 

Commit the pieces individually in the usual way, producing as many commits as you need.

Finally

$ git rebase --continue 
like image 140
Wayne Conrad Avatar answered Oct 06 '22 23:10

Wayne Conrad