Posted 2020-02-06 with tags git, version control

If you've accidentally committed to the wrong branch in git, but haven't yet pushed your changes, here is a quick and easy way to revert the commit, and retain and move your changes to the correct branch.

Here is the description of a soft reset from git help reset:

--soft
    Does not touch the index file or the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

So let's start by executing the soft reset:

git reset --soft HEAD^

The changes remain in your working directory, and the errant commit has been reverted. Now just switch to the desired branch and commit your changes again.

git checkout desired_branch
git commit -a

Now that the commit has been made on the correct branch, push your changes and you're good to go!