Branch Management
The git branch
command has other functions beyond creating and deleting branches. It can also be used for Branch Management.
Listing Branches
When the git branch
command is run without any arguments, it will list all branches of the current repository. The *
character indicates the branch that is currently checked out.
git branch
dev
hot-fix
* main
Adding the -v
option will include the last commit on each branch.
git branch -v
dev 782fd34 Adds a new feature
hot-fix 93b412c Fixes javascript issue
* main 7a98805 Merge branch 'hot-fix'
Merging is a vital part of working with branches, and therefore it is helpful to know which branches have been merged. The --merged
option will list branches that have already been merged. While the --no-merged
option lists those branches that have yet to be merged.
git branch --merged
hot-fix
* main
git branch --no-merged
dev
Deleting Branches
Once a branch has been merged and is no longer needed, the branch can be deleted. To delete a branch, the -d
option is applied to the git branch
command followed by the name of the branch to be deleted.
git branch -d new-branch
NOTE
The command above will fail when deleting the currently checked out branch. If the branch has not been fully merged, Git will require the force delete option (-D
) to delete the branch.
Renaming Branches
The --move
option can be used to rename an existing branch.
# renames master branch to main locally
git branch --move master main
The renamed branch must be pushed to the remote repository to change the branch name remotely.
git push --set-upstream origin main
However, this will cause both the master
and the main
branches to appear on the remote repository. To entirely remove the master
branch from the remote repository, the following command should be used.
git push origin --delete master