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 -dThis 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 -DThis 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) }