Skip to content

Instantly share code, notes, and snippets.

@SteGriff
Last active January 25, 2023 14:42
Show Gist options
  • Save SteGriff/8cbe8949531c6c10c43ab06d1e3f8328 to your computer and use it in GitHub Desktop.
Save SteGriff/8cbe8949531c6c10c43ab06d1e3f8328 to your computer and use it in GitHub Desktop.
Move last git commit to a different branch

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment