In Git, list names of branches with unpushed commi

2019-03-17 06:08发布

问题:

Given a project with several local branches, each tracking some remote branch, is there a command that lists all branches that have unpushed commits? (That is, even if none of those branches are checked out.)

I don't want to see the commits themselves, nor do I want to see branches that are up-to-date, I just want to see which branches are ahead of their remotes.

I have tried git log --branches --not --remotes --simplify-by-decoration --decorate --oneline, but it doesn't seem to show what I need. Running it on my current repo gives no output, but running git status on my current branch shows Your branch is ahead of 'origin/branchname' by 2 commits.

git for-each-ref --format="%(refname:short) %(push:track)" refs/heads and git branch -v both show branches that are up to date as well as ones that need pushing. However, they do both show my current branch as [ahead 2].

Other commands I have found eg. git log @{u}.., git cherry -v list the commits themselves, not the branches.

Side question: why would the output from git log --branches --not --remotes --simplify-by-decoration --decorate --oneline not include branches that git branch -v shows as ahead? Isn't the former command just looking at which refs/heads do not correspond to a known remote; so wouldn't a branch listed as [ahead 2] meet this criteria?

回答1:

The --no-walk option to log seems to do a better job of what I need than --simplify-by-decoration. My full command is:

git log --branches --not --remotes --no-walk --decorate --oneline

...which I've aliased to unpushed.



回答2:

git for-each-ref --format="%(refname:short) %(push:track)" refs/heads

That remain the most precise answer that you can easily parse/grep to get the desired output (like removing up-to-date branches)

You can do so in a bash script that you will call git-xxx (no extension), somewhere in your $PATH or %PATH%.
That script can then be called with git xxx, and will use git bash.
That is portable and will work across platforms (meaning even on Windows, where <Git For Windows>/usr/bin includes 200+ linux commands (grep, sed, awk, xargs, ...)



回答3:

You can also see what branches are not yet merged to master

git checkout master

and then

git branch --no-merged


标签: git branch