Git Branch Commands
Overview
The git branch
command is used to manage branches in a Git repository. Branches allow you to work on separate features or fixes independently from the main codebase. This document covers the basic and advanced usage of git branch
.
Listing Branches
git branch
Lists all local branches in the repository.
Example
This command lists all local branches and highlights the current branch with an asterisk.
git branch -r
Lists all remote branches.
Example
This command lists all branches available on the remote repository.
git branch -a
Lists all local and remote branches.
Example
This command lists all local and remote branches in the repository.
Creating Branches
git branch <branch>
Creates a new branch with the specified name.
Example
This command creates a new branch named feature-branch
.
Deleting Branches
git branch -d <branch>
Deletes a local branch safely, preventing deletion if it contains unmerged changes.
Example
This command deletes the feature-branch
if it has been fully merged into the current branch.
git branch -D <branch>
Forcefully deletes a local branch, regardless of its merge status.
Example
This command forcefully deletes the feature-branch
, even if it has unmerged changes.
Renaming Branches
git branch -m <old-branch> <new-branch>
Renames a local branch.
Example
This command renames the local branch from old-feature-branch
to new-feature-branch
.
git branch -m <new-branch>
Renames the current branch.
Example
This command renames the current branch to new-branch
.
Switching Branches
git checkout <branch>
Switches to the specified branch.
Example
This command switches to the main
branch.
git switch <branch>
Switches to the specified branch (alternative to git checkout
).
Example
This command switches to the main
branch using the git switch
command.
Creating and Switching Branches
git checkout -b <branch>
Creates a new branch and switches to it.
Example
This command creates a new branch named feature-branch
and switches to it.
git switch -c <branch>
Creates a new branch and switches to it (alternative to git checkout -b
).
Example
This command creates a new branch named feature-branch
and switches to it using the git switch
command.
Tracking Remote Branches
git branch --track <branch> <remote>/<branch>
Creates a new local branch that tracks a remote branch.
Example
This command creates a new local branch feature-branch
that tracks the origin/feature-branch
remote branch.
Summary
The git branch
command is crucial for managing branches within your Git repository. It allows you to create, delete, rename, and list branches, as well as switch between them and track remote branches. For more detailed information on each command, refer to the official Git documentation.