Git Switch: Create and Change Branches Safely
Create and switch in one step
In the fresh switch lab, main contains notes.txt with Tea. Use git switch -c to create a branch at the current commit and activate it. By contrast, git branch topic only creates a name. Git 2.23 introduced switch; older clients can use checkout -b and checkout for these branch operations.
git status --shortgit switch -c featuregit branch --show-currentprintf "Milk\n" > notes.txtgit add -- notes.txtgit commit -m "Feature notes"git switch mainThe current branch is feature immediately after creation. After switching back, notes.txt contains Tea again; the Milk commit is still reachable through feature.
Edits can prevent a switch
On main, make an unstaged edit to the file that differs on feature. Git normally refuses to overwrite a local edit during switching. A clean working tree is not always mandatory: non-conflicting edits can travel with you.
printf "Rice\n" > notes.txtgit switch featuregit status --shortgit diff -- notes.txtThe switch is intentionally expected to fail. main remains active and Rice remains in the working file. Read the error rather than repeating with force.
Save the intended work before switching
Here Rice is a desired change to main. Stage and commit it deliberately after reviewing the diff. If the change belongs elsewhere, a new branch at the current commit may be a better home; do not commit unrelated edits blindly.
git add -- notes.txtgit diff --cachedgit commit -m "Main notes"git switch featuregit status --shortThe clean switch now succeeds and the working file contains Milk. Both committed changes survive on their own branches. Switching does not merge them.
Practice
In a new disposable repository, create a topic branch, commit a change, return to main and explain why the file changes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Git Switch: Create and Change Branches Safely — knowledge check
Reason about branch references, snapshots and safe local operations.
Which command creates and activates feature?
What happens to a tracked file when switching between clean branches with different contents?
Git refuses to switch because an edit would be overwritten. What is a safe first action?
Does switching always require a clean working tree?
Which older command creates and activates a branch like switch -c?