Sub topic 4
Creating and switching branches
This chapter assumes you know init, clone, add, commit, status, and log, and that you run Git 2.23 or later, which added git switch. It also assumes you know a branch is a pointer to a commit and that HEAD names the branch you are on.
What creation does
Creating a branch writes one small file that holds a commit hash. It copies no files. The new branch points at the commit you are on, so it takes almost no time or space.
Listing, creating, and switching
git branch
git switch -c feature/login
git branch -v
git switch maingit branchlists local branches. A*marks the current one.git switch -c feature/logincreates the branch at the current commit and switches to it in one step.git branch -vadds the tip commit hash and subject for each branch.git switch mainmovesHEADback tomain.
Switching updates your working directory and index to match the target branch's tip. Files that differ between the two branches change on disk, so reload your editor if it shows stale content.
Other ways to create a branch
git branch hotfixcreates a branch but leaves you where you are.git switch -c hotfix v1.2.0starts the branch at a tag, a commit hash, or another branch instead of the current commit.git switch -returns to the previously checked-out branch.
Older tutorials use git checkout -b name. It does the same job, but git checkout also restores files and detaches HEAD, so git switch is harder to misuse.
Switching with uncommitted changes
Git carries your uncommitted changes to the new branch if they do not collide with files that differ between the branches. If they would be overwritten, Git refuses:
error: Your local changes to the following files would be overwritten by checkout:
app.py
Please commit your changes or stash them before you switch branches.Commit the work, or run git stash and then switch. Do not reach for git switch --discard-changes unless you really want to lose the edits.
Common errors
| Message or symptom | Cause | Fix |
|---|---|---|
| `fatal: a branch named 'x' already exists` | The name is taken. | Pick another name, or `git switch x` to use the existing branch. |
| `fatal: invalid reference: x` | You mistyped the name or never created the branch. | Check `git branch -a`. Add `-c` if you meant to create it. |
| Commits land on `main` by mistake | You forgot to switch before committing. | Run `git branch -v` before you start working. |
Exercise
You are on main with a clean working tree. You run git switch -c fix/typo and make one commit. Which branch points at that new commit, and where does main point?
Show answer
Only fix/typo points at the new commit, and HEAD follows fix/typo. main stays at the commit it pointed to before. Creating a branch only adds a pointer, and a commit moves only the pointer of the branch that is checked out.