How to Delete Branches Locally and Remotely in Git?
When you want to delete local and remote branches in Git, follow these steps:
Delete Local Branches
To delete a local branch, use the git branch command with the -d or -D option. The -d option verifies whether the branch has been fully merged into its upstream branch; if not merged, it prevents deletion to avoid losing work. If you are certain you want to delete an unmerged branch, use the -D option, which is equivalent to git branch --delete --force.
Example:
Suppose you have a branch named feature-x that you have completed and merged. Now you want to delete it:
bashgit branch -d feature-x
If the feature-x branch has not been merged, the above command will fail. In that case, use:
bashgit branch -D feature-x
Delete Remote Branches
To delete a remote branch, use the git push command with the --delete option, followed by the remote repository name and the branch name to delete.
Example:
Suppose the remote repository is named origin, and you want to delete the remote feature-x branch:
bashgit push --delete origin feature-x
This command sends a request to the remote repository to delete the specified branch.
Summary
By following these steps, you can clean up your project repository and remove unnecessary branches. In practice, ensure you notify team members before deleting branches and confirm the branch can be safely deleted; this is a good practice.