You can prune tracking branches in your repo that no longer exist on the remote repo using:
git remote prune [remoteName]
However this will only get rid of the tracking branches and not any local branches you have set up in addition, eg.:
$ git branch
* master
some-remote-branch
$ git remote prune origin
Pruning origin
URL: https://myserver.com/DefaultCollection/_git/Repo
* [pruned] origin/some-remote-branch
$ git branch
* master
some-remote-branch <-- non-tracking branch still here!
Is there a way you can also prune the local non-tracking branches associated with pruned tracking branches, or do you always have to delete these manually?
git can not prune the local branches which tracking branches are deleted.
And the common ways to delete the local non-tracking branches are based on below situations:
If there has a few branches in your local repo, you can delete the local non-tracking branches manually.
You can use the command git branch -a
to compare the remote tracking branches with local branches, and then delete related branch(es) manually.
If there are lots of branches in your git repo, or if you do not want to compare and delete the local non-trackign branches manually, then you can delete the local non-tracking branches automatically by scripts.
Below is the example with shell script to delete the local non-tracking branches automatically (assume master
branch won’t be deleted):
#!/bin/sh
git fetch -p
#checkout HEAD to the branch which you will never delete, here as master won't be deleted
git checkout master
for local in $(git for-each-ref --format='%(refname:short)' refs/heads/)
do
{
if [[ $(git branch -r) =~ $local ]]; then
echo "local branch $local has related tracking branch"
else
git branch -D $local
fi
}
done
Then the local non-tracking branch(es) will be deleted aothmatically.
BTW: except the git remote prune [remoteName]
to prune a tracking branch, you can also use git fetch -p
to prune all the tracking branches.