Managing branches is a fundamental part of working with Git, and there are times when you’ll need to clean up by deleting branches that are no longer in use. This guide will walk you through the steps to delete Git branches both locally and remotely.
1. Deleting a Local Git Branch
Before deleting a branch locally, ensure you’re not currently checked out on the branch you want to delete. Git will prevent you from deleting the branch you’re working on.
Steps to Delete a Local Branch:
1. List the branches to confirm the name of the branch you want to delete:
git branch
This will display a list of all local branches, with the current branch marked by an asterisk (*).
2. Delete the branch:
For a branch that has been fully merged into the current branch:
git branch -d branch_name
If the branch hasn’t been merged, use the force delete option:
git branch -D branch_name
Example:
git branch -D feature-branch
Common Errors:
Error: error: Cannot delete branch ‘branch_name’ checked out at ‘path’
This happens if you’re currently on the branch you’re trying to delete. Switch to another branch using git checkout branch_name or git switch branch_name before retrying.
Error: error: The branch ‘branch_name’ is not fully merged.
This warning prevents accidental deletion of unmerged changes. Use git branch -D branch_name if you’re sure you want to delete it.
2. Deleting a Remote Git Branch
A remote branch resides on a remote repository (e.g., on GitHub or GitLab). To delete it, you’ll need push access to the repository.