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.