List all local branches without a remote

2019-01-13 02:12发布

Problem: I want a way of deleting all the local branches I have that do not have a remote. It's easy enough to pipe the names of the branches into a git branch -D {branch_name}, but how do I get that list in the first place?

For example:

I create a new branch with no remote:

$ git co -b no_upstream

I list all my branches, there's only 1 with a remote

$ git branch -a
master
* no_upstream
remotes/origin/HEAD -> origin/master
remotes/origin/master

What command can I run to get no_upstream as an answer?

I can run git rev-parse --abbrev-ref --symbolic-full-name @{u} and that will show that it has no remote:

$ git rev-parse --abbrev-ref --symbolic-full-name @{u}
error: No upstream configured for branch 'no_upstream'
error: No upstream configured for branch 'no_upstream'
fatal: ambiguous argument '@{u}': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

But as this is an error, it won't let me use it or pipe it to other commands. I'm intending to use this as either a shell script alias'd to git-delete-unbranched or maybe make a super simple Gem like git-branch-delete-orphans

Any help would be appreciated! Thanks

8条回答
劫难
2楼-- · 2019-01-13 02:52

Late edit: better is

git for-each-ref  --format='%(refname:short) %(upstream)'  refs/heads \
| awk '$2 !~/^refs\/remotes/'

on GNU/anything

for b in `git branch|sed s,..,,`; do
    git config --get branch.$b.remote|sed Q1 && echo git branch -D $b
done

If more than a handful of branches were likely there'd be better ways, using comm -23 on the output of git branch|sed|sort and git config -l|sed|sort.

查看更多
狗以群分
3楼-- · 2019-01-13 02:58

This works for me:

git branch -vv | grep -v origin

(if your remote is named anything other than origin, substitute that).

This will list all the branches that aren't tracking a remote, which sounds like what you're looking for.

查看更多
登录 后发表回答