Git Alias to Delete Branches with Gone Remotes
Create a git alias that finds and deletes local branches whose upstream remote-tracking branch has been deleted, cleaning up after merged PRs.
Detailed Explanation
Delete Branches with Gone Remotes
After a PR is merged and the remote branch is deleted, the local branch often remains with a "gone" upstream. This alias finds and removes them:
[alias]
gone = !git fetch -p && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D
Breaking Down the Pipeline
git fetch -pfetches and prunes stale remote-tracking referencesgit branch -vvlists branches with verbose tracking infogrep ': gone]'filters branches whose upstream is marked as "gone"awk '{print $1}'extracts just the branch namexargs -r git branch -Dforce-deletes each branch (the-rflag prevents running with empty input)
Understanding "Gone" Branches
When you create a local branch that tracks a remote branch, and then the remote branch is deleted (e.g., after a PR merge), git branch -vv shows:
feature/login a1b2c3d [origin/feature/login: gone] Add login page
feature/api e4f5g6h [origin/feature/api: gone] Add API routes
main i7j8k9l [origin/main] Latest commit
The : gone] marker indicates the upstream no longer exists.
Why -D Instead of -d?
The alias uses -D (force delete) because the local branch may contain commits that are not reachable from the current branch, even though they were merged via a pull request (which creates a merge commit on the remote). The -d flag would refuse to delete in this case, producing false negatives.
When to Use This vs cleanup
| Alias | Approach | Best for |
|---|---|---|
cleanup |
Deletes branches merged into current branch | Local workflow |
gone |
Deletes branches whose remote was deleted | PR-based workflow |
In PR-based workflows (GitHub, GitLab), gone is usually more accurate because merges happen on the remote, and the local branch may not be recognized as "merged" locally.
Use Case
Use this alias in teams that use pull request workflows where branches are deleted on the remote after merging. Run it weekly to keep your local repository clean. It is the most reliable way to clean up after GitHub's 'Delete branch' button.