To delete local and remote Git branches, follow these steps:
Deleting Local Branches:
-
First, ensure you are not on the branch you want to delete. If you are currently on that branch, switch to a different branch, such as
mainormaster:bashgit checkout mainNote: If your default branch is not
main, use the default branch name for your repository. -
Use
git branch -d <branch_name>to delete the local branch. Here,<branch_name>is the name of the branch you want to delete. Use the-doption if the branch has been fully merged into the upstream branch; use-Dto force delete unmerged branches.bashgit branch -d branch_nameTo force delete an unmerged branch:
bashgit branch -D branch_name
Deleting Remote Branches:
-
Use the
git pushcommand with the--deleteoption to delete the branch from the remote repository. Similarly,<branch_name>is the name of the branch you want to delete.bashgit push origin --delete branch_nameHere,
originis the name of the remote repository (typicallyoriginby default), andbranch_nameis the name of the remote branch you want to delete.
Comprehensive Example:
If you have a local and remote branch named feature-x that you want to delete, follow these steps:
- Switch to a different branch, such as
main:bashgit checkout main - Delete the local
feature-xbranch:bashgit branch -d feature-x - Delete the remote
feature-xbranch:bashgit push origin --delete feature-x
Ensure you back up any important data before performing these operations, as deleting branches is irreversible.