How to Use Git Branch: Commands and Examples
Use
git branch to list branches, git branch <name> to create a new branch, and git checkout <name> or git switch <name> to switch branches. Delete branches with git branch -d <name>. These commands help you manage different versions of your project easily.Syntax
The git branch command manages branches in your Git repository.
git branch: Lists all branches.git branch <branch-name>: Creates a new branch named <branch-name>.git checkout <branch-name>orgit switch <branch-name>: Switches to the specified branch.git branch -d <branch-name>: Deletes the specified branch if merged.
bash
git branch
git branch <branch-name>
git checkout <branch-name>
# or
git switch <branch-name>
git branch -d <branch-name>Example
This example shows how to create a new branch, switch to it, and then list all branches.
bash
git branch feature
git switch feature
git branchOutput
* feature
main
Common Pitfalls
One common mistake is trying to delete a branch that is currently checked out, which Git will not allow. Also, deleting a branch that has unmerged changes will fail unless forced.
Another pitfall is confusing git branch (which only creates or lists branches) with git checkout or git switch (which changes the current branch).
bash
git branch -d feature # Error if 'feature' is the current branch or has unmerged changes git switch main git branch -d feature # Deletes 'feature' branch safely
Output
error: Cannot delete branch 'feature' checked out at '/path/to/repo'
Deleted branch feature (was abc1234).
Quick Reference
| Command | Description |
|---|---|
| git branch | List all branches |
| git branch | Create a new branch |
| git switch | Switch to a branch |
| git checkout | Switch to a branch (older) |
| git branch -d | Delete a merged branch |
| git branch -D | Force delete a branch |
Key Takeaways
Use
git branch to list and create branches without switching.Switch branches with
git switch or git checkout.Delete branches safely with
git branch -d, force delete with -D.Never delete the branch you are currently on; switch first.
Branches help you work on features separately without affecting main code.