Steve Crane
Steve Crane

Reputation: 4440

Git: How do I list local branches that are tracking remote branches that no longer exist?

How can I list any local branches that appear (as per .git/config) to be tracking remote branches that no longer exist? Remote branches are on GitHub in this case but I suspect their location has no relevance.

For example:

  1. I have local branches, a, b, c and d.
  2. a is tracking origin/a and c is tracking origin/c.
  3. b and d are not tracking remote branches.
  4. origin/a has been been merged back into master and was deleted during a repository clean-up; I no longer need to keep local branch a.
  5. If local branch a is checked out to the working tree, running git fetch or git pull results in the error Your configuration specifies to merge with the ref 'a' from the remote, but no such ref was fetched.

How would I produce the list containing only a and any other local branches that appear to be tracking remote branches that no longer exist?

I would like to identify these so that I can delete obsolete local branches I no longer need.

The list should not include local branches b or d that are not tracking remote branches, and also not c that is tracking origin/c, which still exists.

Upvotes: 26

Views: 10589

Answers (4)

Anton Styagun
Anton Styagun

Reputation: 1182

LANG=en git branch --format='%(if:equals=gone)%(upstream:track,nobracket)%(then)%(refname:short)%(end)' | grep '.'

Upvotes: 10

STW
STW

Reputation: 46394

To list your local branches which track deleted remote branches you can use git remote prune --dry-run

For example (assuming your remote repository is named origin):

git fetch
git remote prune origin --dry-run

You can remove the --dry-run option to delete the branches from your local repository

Upvotes: 7

jthill
jthill

Reputation: 60565

git for-each-ref refs/heads --format='%(refname:short) %(upstream)' \
| awk 'NF==1'

will do it. NF is awk's "number of fields", and its default action is print.

Upvotes: 6

Schleis
Schleis

Reputation: 43790

If your local branches are tracking the remote branch you can filter the list of branches so show the ones that do not have a tracking branch with:

git branch -vv | grep -v origin

This will provide some extra information about the last commit that is on the branch but you can filter that out

git branch -vv | grep -v origin | awk '{print $1}'

This will only print the name of the branch that isn't tracking a remote branch.

Upvotes: 21

Related Questions