Branch Management

The git branch command has other functions beyond creating and deleting branches. It can also be used for Branch Managementopen in new window.

Listing Branches

When the git branchopen in new window 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 -vopen in new window 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 --mergedopen in new window option will list branches that have already been merged. While the --no-mergedopen in new window 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 -dopen in new window 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 --moveopen in new window 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