BudiBadu Logo
Samplebadu

Git by Example: Branch Switching

2.43.0

Learn how to navigate between different branches in your repository. This example compares the classic git checkout command with the modern git switch command.

Code

# Switch to an existing branch (old way)
git checkout main

# Switch to an existing branch (new way)
git switch feature-login

# Output:
# Switched to branch 'feature-login'

# Switch to the previous branch (like TV remote)
git switch -

# Output:
# Switched to branch 'main'

# List all branches to see where you are
git branch -a

Explanation

Switching branches updates the files in your working directory to match the version stored in the target branch. It also moves the HEAD pointer to point to the new branch. This allows you to context switch between different tasks, like pausing work on a feature to fix a critical bug on the main branch.

For years, git checkout was the only command for this, but it was also used for restoring files, which confused many users. The git switch command was introduced to do exactly one thing: switch branches. It is safer and easier to understand for beginners.

A handy trick is using git switch - (or git checkout -), which toggles you back to the last branch you were on. This is incredibly useful when you need to quickly check something on another branch and return.

  • Updates working directory files to match the branch
  • Moves the HEAD pointer
  • git switch is preferred over git checkout
  • Use - to toggle to the previous branch

Code Breakdown

2
Classic command to switch to the 'main' branch. While still valid, it is being phased out in favor of switch for this specific purpose.
5
The modern, explicit command to switch branches. If the branch doesn't exist, this command will fail (unless you use -c).
11
Switches to the previously checked-out branch. This is a shortcut that saves you from typing the full branch name when toggling back and forth.
17
Lists all branches, including remote ones (-a). This helps you verify which branch is currently active (marked with *) and what other branches exist.