How to Switch Branch in Git: Simple Commands Explained
To switch branches in Git, use the
git switch <branch-name> command. If you want to create and switch to a new branch, use git switch -c <new-branch-name>.Syntax
The basic command to switch branches is git switch <branch-name>. Here, <branch-name> is the name of the branch you want to move to. To create a new branch and switch to it immediately, use git switch -c <new-branch-name>.
- git switch: Command to change branches.
- <branch-name>: Existing branch to switch to.
- -c: Option to create a new branch and switch to it.
bash
git switch <branch-name> git switch -c <new-branch-name>
Example
This example shows how to switch from the current branch to an existing branch called feature, and how to create and switch to a new branch called bugfix.
bash
$ git branch * main feature $ git switch feature Switched to branch 'feature' $ git switch -c bugfix Switched to a new branch 'bugfix'
Output
Switched to branch 'feature'
Switched to a new branch 'bugfix'
Common Pitfalls
One common mistake is trying to switch to a branch that does not exist without using the -c option, which causes an error. Another is having uncommitted changes that conflict with the target branch, which prevents switching.
Always commit or stash your changes before switching branches to avoid conflicts.
bash
$ git switch non-existent-branch error: pathspec 'non-existent-branch' did not match any branch # Correct way to create and switch: git switch -c non-existent-branch
Output
error: pathspec 'non-existent-branch' did not match any branch
Switched to a new branch 'non-existent-branch'
Quick Reference
| Command | Description |
|---|---|
| git switch | Switch to an existing branch |
| git switch -c | Create and switch to a new branch |
| git branch | List all branches |
| git status | Check for uncommitted changes before switching |
Key Takeaways
Use
git switch <branch-name> to move between existing branches.Use
git switch -c <new-branch-name> to create and switch to a new branch in one step.Always commit or stash changes before switching branches to avoid conflicts.
Check existing branches with
git branch before switching.Errors occur if you try to switch to a non-existent branch without
-c.