How to delete a branch?
In Git, a branch can be deleted locally and in the remote repository. These are different operations.
Deleting a local branch
Safe deletion (recommended)
bash
git branch -d feature/my-feature- deletes the branch only if it has already been merged;
- protects against losing changes.
Force deletion
bash
git branch -D feature/my-feature- deletes the branch even if it has not been merged;
- used when the branch is no longer needed.
Deleting a remote branch
bash
git push origin --delete feature/my-featureDeletes the branch in the remote repository (origin).
Cleaning up references to deleted branches
If a branch has already been deleted on the server but is still shown locally:
bash
git fetch --pruneImportant points
- Deleting a branch does not delete commits if other references point to them.
- You cannot delete the branch you are currently on - you must switch first.
- Feature branches are usually deleted after being merged into the main branch.
Summary
- Locally:
git branch -d/git branch -D - Remotely:
git push origin --delete <branch>
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.