Switching Branches

Use git switch (or git checkout) to move between branches, optionally creating one.

Syntaxgit switch <branch> git switch -c <new-branch>

Creating a branch does not move you to it. Use git switch to change your working directory to another branch.

switch vs checkout

git switch is the modern, clearer command for changing branches. git checkout still works and does the same thing, but it also does many other jobs, which makes it easy to confuse.

  • git switch main β€” move to an existing branch.
  • git switch -c feature β€” create a branch and switch to it in one step.

Example

Example Β· bash
# Create and switch in one command
git switch -c login-page

# ...make changes and commit...

# Go back to main
git switch main

When to use it

  • A developer switches from main to a feature branch to continue coding a new API endpoint.
  • A team member checks out a colleague's remote branch locally to review and test the code before approving.
  • A developer creates and immediately switches to a new branch in one command to start a hotfix.

More examples

Switch to an existing branch

The modern git switch command moves HEAD to the named branch, updating the working directory to match.

Example Β· bash
git switch feature/user-auth
# Switched to branch 'feature/user-auth'

Create and switch in one step

The -c flag creates the branch and switches to it atomically, saving a separate git branch command.

Example Β· bash
# Modern syntax
git switch -c feature/payments

# Equivalent classic syntax
git checkout -b feature/payments

Check out a remote branch locally

Downloads the remote branch as a local tracking branch so you can build, test, and push changes back to it.

Example Β· bash
# Fetch latest remote info
git fetch origin

# Create a local tracking branch from remote
git switch --track origin/feature/dark-mode
# Branch 'feature/dark-mode' set up to track 'origin/feature/dark-mode'

Discussion

  • Be the first to comment on this lesson.
Switching Branches β€” GitHub | SoundsCode