Course contentsShow
← Computer Science
Lesson 2190 of 2,87249. Version Control with GitFree lesson

Deleting Branches

Learn safe practices for deleting merged and unmerged branches using git branch -d and -D flags.

Deleting Branches

You'll learn how to safely remove branches from your Git repository once they're no longer needed.

After merging a feature branch into your main branch, that feature branch often becomes obsolete. Keeping unnecessary branches clutters your repository and makes navigation harder. Git provides two flags for deleting branches, each with different safety guarantees.

Safe Deletion with -d

The git branch -d flag performs a safe delete. It only removes a branch if Git can confirm that the branch has been fully merged into your current branch (or upstream). This prevents accidental loss of work:

git branch -d feature-login

If the branch contains unmerged changes, Git will refuse to delete it and show a warning. Think of this as a safety lock—Git is protecting you from losing commits that exist only on that branch.

Force Deletion with -D

Sometimes you genuinely want to delete a branch with unmerged work—perhaps an abandoned experiment or a failed approach. The git branch -D flag (capital D) forces deletion regardless of merge status:

git branch -D experimental-refactor

This is like overriding the safety lock. Use it cautiously, because once deleted, recovering those commits becomes difficult (though not always impossible—Git retains orphaned commits temporarily).

When to Use Each

Use -d as your default—it's the safe choice after merging branches. Only reach for -D when you're certain you want to discard unmerged work permanently.

Key Takeaway: Use git branch -d to safely delete merged branches; use git branch -D only when you intentionally want to discard unmerged changes. Always verify what you're deleting before using the force flag.