Here are some common git
branch commands, along with explanations of how to use them:
Basic Git Branch Commands
List Branches
To list all branches (both local and remote):git branch
To list all branches, including remote ones:
git branch -a
Create a New Branch
To create a new branch:git branch <branch-name>
Example:
git branch feature/login
Switch to a Different Branch
To switch to an existing branch:git checkout <branch-name>
Example:
git checkout feature/login
Note: In newer versions of Git, you can use the
git switch
command:git switch <branch-name>
Create and Switch to a New Branch
To create a new branch and immediately switch to it:git checkout -b <branch-name>
Or, using the newer command:
git switch -c <branch-name>
Rename a Branch
To rename the current branch:git branch -m <new-branch-name>
To rename a branch that you’re not currently on:
git branch -m <old-branch-name> <new-branch-name>
Delete a Branch
To delete a local branch:git branch -d <branch-name>
If the branch hasn’t been merged, you may need to use
-D
(force delete):git branch -D <branch-name>
Show Branch Details
To show details of the current branch:git status
Merge a Branch into the Current Branch
To merge another branch into your current branch:git merge <branch-name>
Example:
git merge feature/login
List Remote Branches
To list all remote branches:git branch -r
Delete a Remote Branch
To delete a remote branch:git push origin --delete <branch-name>
Push a Branch to Remote
To push a local branch to a remote repository:git push origin <branch-name>
Fetch and Update Remote Branches
To fetch all remote branches:git fetch --all
Track a Remote Branch
To track a remote branch when you check out a new branch:git checkout --track origin/<branch-name>
Or using the newer
switch
:git switch --track origin/<branch-name>
Useful Tips
Check Which Branch You Are On: To check the current branch you’re on:
git branch
The current branch will have an asterisk (*) next to its name.
Create a Branch from Another Branch
To create a new branch from a specific branch:git checkout -b <new-branch-name> <existing-branch-name>
Switch Back to Previous Branch
To switch back to the branch you were on previously:git checkout -
These commands will help you navigate, manage, and organize your branches within Git.