git – List all local branches without a remote

Question:

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 without a remote:

I list all my branches, and there’s only one with a remote

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:

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

Answer:

I recommend using git branch --format to specify the exact output you want from the git branch command. By doing that, you can pull out just the refname and the upstream, like this:

It outputs the branches along with the remote branches if they exist, in the following format:

Once you have this nicely formatted output, it’s as easy as piping it through awk to get your list:

Results in the following output:

The awk portion prints the first column if there is no second column.

Bonus: Create an alias

Make it easy to run by creating an alias in your global .gitconfig file (or wherever):

Bonus: Remote Filtering

If for some reason you have multiple tracking remotes for different branches, it’s easy enough to specify which remote you want to check against. Just add the remote name to the awk pattern. In my case, it’s origin so I can do this:

Important: The backslash needs to be escaped in the alias or else you will have an invalid gitconfig file.


Previous Answer

The previous answer was functionally similar, but used the following as it’s starting point. Over time, commenters have pointed out that a regex is unreliable due to the variance possible in a commit message, so I no longer recommend this method. But, here it is for reference:

I recently discovered git branch -vv which is the “very verbose” version of the git branch command.

It outputs the branches along with the remote branches if they exist, in the following format:


Once you have this nicely formatted output, it’s as easy as piping it through cut and awk to get your list:

Leave a Reply