How can I create and switch to a local Git branch without losing work?
Quick answer
Run git status before switching so you can see whether you have edits to preserve. To create a local branch from your current commit and switch to it in one step, run git switch -c <branch-name>. Git normally stops if switching would overwrite local changes. If your work is unfinished, commit or stash it first; do not use --discard-changes when you want to keep it. A branch name points to a commit, and creating one alone does not switch branches. [S1] [S2]
The question, the details, the next step.
A practical checklist
Run
git statusbefore switching and review the changes it lists.Decide which edits are ready to commit and which should be stashed.
Preserve unfinished or important work before retrying a blocked switch.
Use
git switch -c <branch-name>to create a branch from the current commit and switch to it.Avoid
--discard-changeswhen you want to keep local edits.
A few more useful answers
Does `git branch <name>` switch me to the new branch?
No. It creates a branch pointing at the current HEAD by default, but does not switch the current branch. Use git switch <name> afterward, or use git switch -c <name> to create and switch in one step. [S2]
What does `git switch --merge` do with local edits?
It attempts to carry local modifications across to the target branch. If reapplying them conflicts, Git may leave conflicts to resolve; it is not a guarantee that every switch will be clean. [S1]
Sources
References used for this guide.
- [S1] Git - git-switch Documentation git-scm.com · Checked
- [S2] Git - git-branch Documentation git-scm.com · Checked
