Skip to main content

Moving git commits to a different branch

  • Happens to me nearly every week:

  • I forget to create a new branch before I start coding, so all my commits end up on the main branch

  • Then, I get ready to push my changes and open a PR and finally realize that I’d be pushing my changes directly to production! (Or at least, I would be if this [add link] branch protection rule wasn’t in place.)

  • I like my commits, but I want to move them to a feature branch

  • If this happens to you, git cherrypick is what you need

    • Or just undo the commits?
    • cherrypick vs just checkout new branch
  • What if my feature is…

    • Not yet created?
    • Previously created?
  • What if I’ve pushed my changes to remote?

  • Lazygit method? CLI?

Count how many commits to move

  1. From your main branch, use git log to view your recent commits:

    # command
    git log
     
    ## output
    commit HASH (HEAD -> trunk)
    Author: ME
    Date:   TODAY
     
        commit message
     
    commit HASH
    Author: ME
    Date:   TODAY
     
        commit message
     
    commit HASH (origin/trunk, origin/HEAD)
    Author: ME
    Date:   TODAY
     
        commit message
     
    :
  2. Type q to exit the git pager

  3. Count how many commit HASH lines you see before the commit HASH (origin/main, origin/HEAD) line (in the example output above, there are two)

Moving commits to a new branch

  1. Create a new branch that will include all of the commits currently on your main branch (without switching to it):

    git branch new-feature
  2. While still on your main branch, move it back by the number of commits you want to move (in this case, two) to reset it to how it was before you committed:

    git reset --keep HEAD~2
  3. Check out your new branch so you can resume working:

    git checkout new-feature

Moving commits to an existing branch

  1. Check out the existing branch you want to move your commits to:

    git checkout existing-feature
  2. Merge main into existing-feature:

    git merge master
  3. Go back to the main branch:

    git checkout main
  4. Move the main branch back by the number of commits you just moved (in this case, two):

    git reset --keep HEAD~2
  5. Check out your new branch so you can resume working:

    git checkout existing-feature
  • That’s how you move commits you accidentally main to your main branch to a new or existing feature branch where they belong.
  • If you need to move commits from a branch other than main, …. (is that when you’d use git checkout instead? is my solution only valid for moving commits from main)
  • It’s also only valid for moving the lastest commit(s)

Further reading

Inbox

  • Cherry-picking (copying a commit from one branch to another) does not delete the original commit. If you want to effectively move the commit to the new branch, you need to go back and delete the original commit after copy/pasting it.