To move the most recent commit(s) to a new branch in Git, follow these steps:
Step-by-Step Guide
- Check Current Commit History:
Usegit log
to confirm the commit(s) you want to move.
git log --oneline
- Create a New Branch that includes the recent commit(s):
git branch new-branch-name
- This branch will point to the current commit (HEAD), preserving the recent commits.
- Reset the Current Branch to remove the commits:
git reset --hard HEAD~N # Replace `N` with the number of commits to move
- Example:
HEAD~2
moves the last 2 commits to the new branch. - Note: This deletes the commits from the current branch (use with caution!).
- Checkout the New Branch to continue working:
git checkout new-branch-name
Example
Move the last 3 commits from main
to a new branch feature/login
:
# Create a new branch containing the latest commits
git branch feature/login
# Reset the current branch (e.g., main) to discard the last 3 commits
git reset --hard HEAD~3
# Switch to the new branch
git checkout feature/login
Key Notes
- Uncommitted Changes: Ensure all changes are committed or stashed before resetting.
- Pushed Commits: If the commits were already pushed, use
git push --force
to update the remote (risky on shared branches). - Safety Check: Use
git log
to verify the state before and after the reset.
Visual Workflow
Before: main [A -> B -> C -> D (HEAD)]
After:
main [A -> B]
feature/login [C -> D (HEAD)]
By following these steps, you can cleanly move recent commits to a new branch!