0
0
GitHow-ToBeginner · 3 min read

How to Create and Switch Branch in Git: Simple Commands

Use git branch <branch-name> to create a new branch and git checkout <branch-name> to switch to it. Alternatively, use git switch -c <branch-name> to create and switch in one step.
📐

Syntax

git branch <branch-name>: Creates a new branch named <branch-name> but stays on the current branch.
git checkout <branch-name>: Switches to the branch named <branch-name>.
git switch -c <branch-name>: Creates and switches to the new branch in one command.

bash
git branch <branch-name>
git checkout <branch-name>
git switch -c <branch-name>
💻

Example

This example shows how to create a branch named feature and switch to it using both the two-step and one-step methods.

bash
git branch feature
# Creates the branch 'feature'
git checkout feature
# Switches to the 'feature' branch

# Or create and switch in one step:
git switch -c feature
Output
Switched to branch 'feature'
⚠️

Common Pitfalls

  • Trying to switch to a branch that does not exist causes an error.
    Error: error: pathspec 'branch-name' did not match any file(s) known to git
  • Using git checkout to create and switch branches is older; prefer git switch -c for clarity.
  • Forgetting to commit changes before switching branches can cause conflicts or lost work.
bash
git checkout new-branch
# Error if 'new-branch' does not exist

git switch -c new-branch
# Correct way to create and switch
Output
error: pathspec 'new-branch' did not match any file(s) known to git Switched to a new branch 'new-branch'
📊

Quick Reference

CommandDescription
git branch Create a new branch without switching
git checkout Switch to an existing branch
git switch Switch to an existing branch (modern)
git switch -c Create and switch to a new branch

Key Takeaways

Use git switch -c <branch-name> to create and switch branches in one step.
Always commit or stash changes before switching branches to avoid conflicts.
git branch <branch-name> only creates a branch; use git checkout or git switch to switch.
Avoid switching to non-existent branches without creating them first to prevent errors.
Prefer git switch commands over git checkout for branch switching in modern Git versions.