← Git

Branches

How do you create a branch and how do you switch to it?

Show answer — try answering out loud first

You create a branch with git branch <nombre> and switch to it with git switch <nombre> (or the old git checkout <nombre>). To create and switch in a single step: git switch -c <nombre> (or git checkout -b <nombre>).

There are two actions: creating the branch and moving to it.

  • git branch feature: creates the feature branch but leaves you where you are. It doesn't move you.
  • git switch feature: moves you to the feature branch (moves HEAD there).
  • git switch -c feature: creates and switches in a single command. It's the most common one day to day.

git switch is the modern command (since Git 2.23) for switching branches. Before, git checkout was used, which still works but does too many things (switching branches, restoring files...), which is why they split it into switch (branches) and restore (files).

# Create a branch (without moving to it)
git branch nueva-feature

# Switch to an existing branch
git switch nueva-feature
# Output: Switched to branch 'nueva-feature'

# Create and switch in a single step (the most used)
git switch -c otra-feature
# Output: Switched to a new branch 'otra-feature'

# Equivalent with the old checkout command
git checkout -b otra-feature

# Go back to the main branch
git switch main

# Delete a branch you no longer need (once merged)
git branch -d nueva-feature

Running git branch feature and believing you're already working on feature, when in reality branch only creates it but doesn't move you: you're still on the previous branch. That's why it's better to use git switch -c feature, which creates and switches at once. Another mistake: trying to delete the branch you're currently on (Git doesn't allow it; switch to another one first).

"I create a branch with git branch nombre, but that doesn't move me to it; to switch I use git switch nombre. Day to day I almost always use git switch -c nombre, which creates the branch and switches me in a single step; the old equivalent is git checkout -b. switch is the modern command for branches, while checkout did too many things at once."

Quick challenge

What is the difference between git branch feature and git switch -c feature?

Show answer

git branch feature only creates the branch, but leaves you on the current branch. git switch -c feature creates and switches you to the feature branch in a single step (moves HEAD there). The second is the most used shortcut when you're going to start working on the new branch right away.