How to move your most recent Git commit to a new branch
Today I learnt …
If you’re anything like me you’ll have found yourself writing new code and accidentally committing it to the default branch (usually master
or main
). This might be alright for your personal repos, but when you’re working in a larger team and collaborating on a project using a branch-based workflow (like GitHub flow), then you need to move that commit to a new branch before you push the code.
One way to do this would be to ‘undo’ the commit: rewind your repository history so it’s as if that commit never happened, but with your local files still modified. However, if you do that, you lose the detailed commit message you spent ten minutes writing (you did write a good commit message, didn’t you?). No, what you want to do is create a new branch that includes your latest commit, and then remove the commit from your default branch.
So what you’ve done so far is commit your new code to the master
branch by accident:
To fix that, you should branch off from the tip of master
and then move master
back one commit:
That last line, git reset --soft HEAD^
, will remove the last commit from master
and the files you changed will still be modified but staged. (If you have more than one commit to remove, you can use HEAD~3
instead of HEAD^
, where 3
is the number of commits you want to remove. You actually have loads of options available.)
Now you’ve cleaned that up, you can unstage the modified files and then push the new branch:
And now no-one’s any the wiser. You have a clean master
branch, a new branch with your new code, and you’re free to carry on adding new commits to the branch.