Deleting Branches

Remove branches locally and on the remote once their work is merged.

Syntaxgit branch -d <branch> git push origin --delete <branch>

After a branch is merged you no longer need it. Deleting merged branches keeps your list tidy.

  • git branch -d feature — delete a local branch (safe: refuses if unmerged).
  • git branch -D feature — force-delete even if unmerged.
  • git push origin --delete feature — delete the branch on GitHub.

On GitHub, the pull request page offers a Delete branch button after merging.

Example

Example · bash
# Delete locally after merging
git branch -d login-page

# Delete the copy on GitHub
git push origin --delete login-page

When to use it

  • A developer deletes a merged feature branch after the pull request is closed to keep the branch list tidy.
  • A CI pipeline automatically deletes the remote branch once a pull request is merged via GitHub's auto-delete setting.
  • A team lead force-deletes a stale experiment branch that was never merged after the idea was abandoned.

More examples

Delete a merged local branch

The -d flag only succeeds if the branch has been fully merged, preventing accidental loss of unmerged work.

Example · bash
# Confirm the branch is fully merged
git branch --merged main
#   feature/user-auth

# Safe delete (fails if unmerged)
git branch -d feature/user-auth

Delete a remote branch

Pushes a deletion instruction to the remote, then prunes stale local tracking refs so git branch -a stays clean.

Example · bash
# Delete the remote branch on origin
git push origin --delete feature/user-auth

# Remove the stale remote-tracking ref locally
git fetch --prune

Force-delete an unmerged branch

The uppercase -D overrides the safety check; the reflog note shows the commits are not immediately gone.

Example · bash
# Branch was never merged but is no longer needed
git branch -D experiment/abandoned-feature

# The commits can still be recovered via reflog
git reflog | grep experiment/abandoned-feature

Discussion

  • Be the first to comment on this lesson.