Move recent commits to another branch

Sometimes I end up making commits on a main branch, while I wanted to make them on a feature branch.

Say we made three commits we want to move to another branch. We can follow those steps:

# If the feature branch does not exist, create it
git switch -C feature-branch
# Otherwise, switch to it
git switch feature-branch
git merge main
git push origin feature-branch # Be sure to save commits before deleting them from main branch
git switch - # Go back to main branch
git reset --hard HEAD~3 # Go back 3 commits, so all the commits we made are deleted from main branch
git switch - # Go back to feature branch

This snipped is adapted from an excellent StackOverflow post.

Join my mailing list

Get monthly insights, personal stories, and in-depth information about what I find helpful in web development as a freelancer.

Email advice once a month + Free XState report + Free course on XState

Want to see what it looks like? View the previous issues.

I value your privacy and will never share your email address.