Skip to content

Instantly share code, notes, and snippets.

@vimkin
Created May 14, 2025 09:02
Show Gist options
  • Select an option

  • Save vimkin/a0839d02b6580c0de886575f4113299c to your computer and use it in GitHub Desktop.

Select an option

Save vimkin/a0839d02b6580c0de886575f4113299c to your computer and use it in GitHub Desktop.
A guide for cleaning up stale local Git branches. This gist explains how to remove branches whose upstream remotes have been deleted, covering differences between git branch --merged and git branch -v based on the [gone] marker.

In case you are using a typical Git workflow, where merged branches are removed from the remote repository (e.g., GitHub, GitLab), you may find yourself with a lot of stale local branches that have no upstreams.

A common suggestion to clean up these local branches is to run:

git fetch --prune
git branch --merged | egrep -v 'master|dev|main|staging' | xargs git branch -d

This command works only if you use a merge (not rebase) strategy and it only deletes branches that have been merged into your current branch (for example, you are in main now).

Note

All the listed commands below will not touch any local branches that never had an upstream, since they are not marked with [gone] by git branch -v.

A better approach for the workflow addressing the issues listed above is:

git fetch --prune
git branch -v | grep 'gone]' | awk '{print $1}' | xargs -r git branch -D

This command deletes all local branches whose upstream has been removed, git branch -v marks these with [gone]. The remaining part of the command extracts the branch names and force-deletes them with git branch -D. Force delete because rebased branches are, technically, never really merged.

Bonus for https://www.nushell.sh users, here is an equivalent command:

git fetch --prune
git branch -v | lines | where $it =~ "gone]" | each { |it| git branch -D (echo $it | str trim | split row -r "\s+" | first) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment