Git & GitHub ยท Chapter 15 of 42

Creating and Switching Branches

To start work on something new without disturbing `main`, you create a new branch and switch to it. Git provides both the modern `git switch` command and the older, more versatile `git checkout` command.

Creating and switching branches is fast and cheap, so it's common practice to create a new branch for every feature, bug fix, or experiment.

Syntax
git branch <name>
git switch <name>
git switch -c <name>

Creating a branch

Run `git branch branch-name` to create a new branch without switching to it, or `git switch -c branch-name` to create and switch in one step.

Switching branches

Use `git switch branch-name` (modern) or `git checkout branch-name` (older) to move your working directory to a different branch.

Example 1 (bash)
git switch -c feature-login
Output
Switched to a new branch 'feature-login'

Creates a new branch named feature-login and switches to it immediately.

Example 2 (bash)
git switch main
Output
Switched to branch 'main'

Switches back to the main branch from wherever you currently are.

Key points

  • git branch name creates a branch without switching to it.
  • git switch -c name creates and switches in one command.
  • git switch (or git checkout) moves you between existing branches.
  • Uncommitted changes can block switching branches in some cases.
๐Ÿ’ก Note: If switching branches fails due to uncommitted changes, either commit, stash, or discard them first.

๐Ÿ“ Quick Quiz

1. Which command creates and switches to a new branch in one step?

2. What does git switch main do?

3. What can prevent switching branches?