A very common development strategy with Git is to create a new branch for every feature and bug you work on, then once the code passes code review, to then merge it to the correct shared branch. The problem then becomes that you end up with a bunch of branches over time that you no longer need. We can use some simple shell commands to clean up these branches.

The Code

# Stop tracking any remotes that no longer exist
git fetch -p

# We output the branch list to a file so we can edit it and 
# decide which branches we wish to remove
git branch -vv | grep ': gone' | awk '{print $1}' > branch-list

# Remove the orphaned branches
cat branch-list | xargs git branch -D

If you are using the Fish shell, you can also use this function to turn this into a one liner:

function gpb
	git fetch -p
	git branch -vv | grep ': gone' | awk '{print $1}' > branch-list
	
	set -l line_count (wc -l branch-list | awk '{print $1}')
	if [ $line_count -gt 0 ]
		vim branch-list
		cat branch-list | xargs git branch -D
	else
		echo "No branches to purge"
	end

	rm branch-list
end