How to move accidentally committed changes to a brand new branch in git?

Moving between different branches is tricky if you don't remember all the steps, but you can always bookmark this page.

# create a new branch from the current state of master
git branch some-new-branch-name
# this is were your commit will live :)
# now go back to master
git checkout master
# remove the commit from the master branch
git reset HEAD~ --hard
# whoola!! you are back on track

the other way of doing this:

# undo the last commit, but leave the changes available
git reset HEAD~ --soft
git stash
# move to the correct branch
git checkout name-of-the-correct-branch
git stash pop
git add . # or add individual files
git commit -m "your message here"
# now your changes are on the correct branch

Many people suggest using cherry-pick for this situation, too, so take your pick on whatever makes the most sense to you!

yet another way:

git checkout name-of-the-correct-branch
# grab the last commit to master
git cherry-pick master
# delete it from master
git checkout master
git reset HEAD~ --hard
Originally Posted On: OhShitGit

Subscribe to GIT.WTF!?!

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]