To move existing, uncommitted work to a new branch in Git, follow these methods:
Method 1: Directly Create a New Branch (Without Stashing)
Use this if you don’t need to return to the original branch immediately.
- Create and switch to the new branch (your uncommitted changes remain in the working directory):
git checkout -b new-branch
- Add and commit the changes on the new branch:
git add . # Stage all changes (including untracked files)
git commit -m "Your message"
- Verify the original branch is unchanged:
git checkout original-branch # Changes are now only in `new-branch`
Method 2: Stash Changes and Apply to the New Branch
Use this if you need to keep the original branch clean (e.g., to switch back later).
- Stash your uncommitted changes (saves both staged and unstaged work):
git stash
- Create and switch to the new branch:
git checkout -b new-branch
- Apply the stash to the new branch:
git stash pop # Restores changes and deletes the stash
- Commit the changes:
git add .
git commit -m "Your message"
Handling Specific Scenarios
- Staged Changes Only:
git stash --keep-index # Stash only unstaged changes, keeping staged ones
git checkout -b new-branch
git commit -m "Commit staged changes"
git stash pop # Restore unstaged changes (if needed)
- Untracked Files:
Include untracked files in the stash:
git stash -u # Stash untracked files too
Key Notes
- Why Use
git checkout -b
?
Creates a new branch from the current commit, preserving your uncommitted work in the working directory. - Avoid Losing Work:
Always stash or commit changes before switching branches if Git warns about overwriting files. - After Moving:
Your original branch (main
,develop
, etc.) will no longer have the uncommitted changes once they’re committed to the new branch.
Example Workflow
# Start on `main` with uncommitted changes
git status # Shows modified/file.txt
# Method 1: Directly create a new branch
git checkout -b feature/new-work
git add .
git commit -m "Add new work"
# Method 2: Stash and apply
git stash
git checkout -b feature/new-work
git stash pop
git add .
git commit -m "Add new work"
Troubleshooting
- “Your local changes would be overwritten” Error:
Stash or commit changes before switching branches. - Accidentally Committed on the Wrong Branch:
Usegit reset
to undo the commit, then move the changes:
git reset HEAD~1 # Undo the last commit (keeps changes in working directory)
git stash
git checkout correct-branch
git stash pop
Choose the method that fits your workflow!