So you've finished reviewing a bunch of work from your team and several new features have been merged to master and deployed. And now you have a branch or two that you're working on mixed in with branches that are no longer needed. The branches have been deleted on your remote repo (Github, for example), but you still have local copies and references to the remote branches that are gone.

List your branches

Before you get started, look at the branches in your repo and make sure you have an idea which ones you're trying to delete.

> git branch -a

Remove your local branches

Remove the local branches that have already been merged on your remote repo. There are multiple steps involved, so let's construct the full command one piece at a time.

List remote branches

List the branches on your remote repo (named origin) that have been merged with the primary branch (usually master) and deleted.

> git remote prune origin --dry-run

The --dry-run option shows the branches that will be removed, but doesn't do it yet. Don't worry, we'll get there eventually.

Extract branch names

Take the output of the git remote prune command and trim off everything except the name of the branch, using the pipe operator (|) and the sed command.

> git remote prune origin --dry-run | sed -n -e 's/^.*origin\///p'

Delete each branch

⚠️ This will delete branches without asking you for confirmation. Make sure you understand how this works before you use it. Test the previous steps if you're not confident that you're deleting the branches you want to remove.

Pass your list of branches to the delete branch command (git branch -d), using the pipe operator (|) combined with the xargs command. This runs the delete command once using each branch name.

> git remote prune origin --dry-run | sed -n -e 's/^.*origin\///p' | xargs git branch -d

Remove your remote branches

Using the same git remote prune command, delete the references to the remote branches.

> git remote prune origin

Check your branches

If you want, take another look at your branches. Revel in the clean, tidy list of branches you're now working with.

git branch -a

Combine all the things

git remote prune origin --dry-run | sed -n -e 's/^.*origin\///p' | xargs git branch -d
git remote prune origin
git branch -a

Automation/shortcuts

I like to run these steps as a TextExpander snippet. A few keystrokes (I use gitclean) and you've removed unnecessary local branches, cleaned up your list of remote branches, and get a look at the branches you're still working with. 🎉

Related

My typical git workflow.