SteGriff

Blog

Next & Previous

Move last git commit to a different branch

So you committed to main instead of your feature branch? Oops! But it’s ok. All commits in git are special little things that are easy to chip up and kick around ⚽

If you need to do any sleuthing first, use

git log

The Process

I already created the target feature branch

If you created the feature branch on remote first (in GitHub or DevOps), run:

git fetch

Checkout the branch where you should have put the commit:

git checkout my-branch

Now merge main into it (feels wrong but is right)

git merge main

You can git push your feature branch changes at this point, if you want.

I didn’t create the feature branch yet

Ok, so you’re on main which has the latest commit that should be in the branch instead. Simply:

git checkout -b my-new-branch

And it will be copy of main including your new commit.

Use git push -u origin my-new-branch on your feature branch to push it up to the remote.

Moving main back

Checkout main, then move it back however many commits you want:

git checkout main
git reset --keep HEAD~1

And you’re done!

You can use git log for your satisfaction.

Commit early, commit often 🦕