0
0
GitHow-ToBeginner · 3 min read

How to Delete a Branch in Git: Simple Commands Explained

To delete a local branch in Git, use git branch -d branch_name. To force delete, use git branch -D branch_name. To delete a remote branch, use git push origin --delete branch_name.
📐

Syntax

Here are the commands to delete branches in Git:

  • Delete local branch safely: git branch -d branch_name deletes the branch only if it is fully merged.
  • Force delete local branch: git branch -D branch_name deletes the branch even if it is not merged.
  • Delete remote branch: git push origin --delete branch_name removes the branch from the remote repository.
bash
git branch -d branch_name

git branch -D branch_name

git push origin --delete branch_name
💻

Example

This example shows how to delete a local branch named feature1 safely, force delete it, and then delete the same branch from the remote repository.

bash
$ git branch
  main
* feature1

$ git branch -d feature1
Deleted branch feature1 (was 9a8b7c6).

$ git branch -D feature1
error: branch 'feature1' not found.

$ git push origin --delete feature1
To https://github.com/user/repo.git
 - [deleted]         feature1
Output
$ git branch main * feature1 $ git branch -d feature1 Deleted branch feature1 (was 9a8b7c6). $ git branch -D feature1 error: branch 'feature1' not found. $ git push origin --delete feature1 To https://github.com/user/repo.git - [deleted] feature1
⚠️

Common Pitfalls

Common mistakes when deleting branches include:

  • Trying to delete the branch you are currently on. Git will prevent this.
  • Using -d to delete a branch that is not fully merged, which causes an error.
  • Forgetting to delete the remote branch separately after deleting locally.

Always check your current branch with git branch before deleting.

bash
$ git branch -d feature1
error: The branch 'feature1' is not fully merged.
If you are sure you want to delete it, use 'git branch -D feature1'.
Output
error: The branch 'feature1' is not fully merged. If you are sure you want to delete it, use 'git branch -D feature1'.
📊

Quick Reference

CommandDescription
git branch -d branch_nameDelete local branch if fully merged
git branch -D branch_nameForce delete local branch
git push origin --delete branch_nameDelete remote branch

Key Takeaways

Use 'git branch -d branch_name' to safely delete a local branch after merging.
Use 'git branch -D branch_name' to force delete a local branch if needed.
Delete remote branches with 'git push origin --delete branch_name'.
Never delete the branch you are currently on; switch branches first.
Always confirm branch deletion to avoid losing important work.