Introduction
Branches in Git are an integral part of any development and deployment workflow. In this post, I will go over what are branches and the different commands that can be used with branches using the Git CLI.
What are branches?
Branches in Version Control Systems (VCS) such as Git, provide a means to diverge from the main branch without affecting the main branch. This gives developers the capability of developing new features, fixing bugs or even separating code by development branches (e.g. Release, Beta, Alpha).
Here are a list of commonly used commands for branches in Git:
List Local Branches in a Repository
git branch
List All Remote Branches in a Repository
git branch -a
Create a Branch and Switch to it
git branch nameOfBranch
git checkout nameOfBranch
Create a Branch and Immediately Switch to it
git checkout -b nameOfBranch
Rename a branch
git branch -m oldNameOfBranch newNameOfBranch
Delete a local branch
git branch -d nameOfBranch
NOTE: This is considered a “safe operation” since Git will prevent you from deleting the branch if there are changes that haven’t been merged with the main branch.
Delete a remote branch
git push origin --delete nameOfRemoteBranch
List branches that have been merged
git branch --merged
List branches that have been merged into a specific branch
git branch --merged nameOfBranch
List branches that have not been merged
git branch --no-merged
Merge branch into main branch
Switch to main branch first: git checkout master
Merge branch into main branch: git merge nameOfBranchToBeMerged
Synchronize list of branches
git fetch -p
-p
stands for prune. The above command excludes any deleted branches from the list to be displayed to the user.
List the most recent commit by branch
git branch -v
List the most recent commit along with its upstream by branch
git branch -vv
List branches by commit date (Ascending)
git branch --sort=committerdate
List branches by commit date (Descending)
git branch --sort=-committerdate