Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list all local tracking branches not pushed in git?

Tags:

git

branch

I'm working in a git repository on multiple tracking branches, and by the end of the day I don't know if I pushed all my work in all branches.

Is there a git command showing which branches are not pushed, so I can checkout and make the pull, merging if necessary and then push?

like image 532
Phate01 Avatar asked Oct 25 '25 03:10

Phate01


1 Answers

Assumption (or definition): by tracking branch you mean a branch which has an upstream set, and that upstream refers to a remote-tracking name. For instance, if branch develop has origin/develop as its upstream, that one counts; but if branch test has develop set as its upstream, that one does not count.

A possible command sequence to use in this case is:

git fetch

followed by:

git branch -vv | grep origin/

The output will resemble this:

* master          083378cc35 [origin/master] commit subject line
  xyz             8dbdf339cd [origin/xyz: ahead 1, behind 13] another subject line

which tells us that master is up to date but xyz is out of sync with its remote counterpart.

Note that if the upstream in question is not named origin, you will need to change the grep command accordingly. You may also need more than one git fetch, or you may want to use git fetch --all. (You may also want to use git fetch --prune or set fetch.prune to true, but this is independent of everything else here.)


It's possible to write a fancier script that prints only the names, skips branches that are in sync, and so on. If you want to do that, use git for-each-ref to enumerate references in the refs/heads/ namespace. These are your branch names. For each name, test whether it has an upstream setting and if so, get the hash ID of its upstream. Compare that to the hash ID of the branch. Also, check whether the upstream is a local branch (the test example above, where the upstream is develop) or a remote-tracking name.

If the upstream is a remote-tracking name and the hash IDs of the local name and the upstream differ, the branch is out of sync with its remote counterpart. To get the ahead and/or behind counts, use:

git rev-list --count --left-right local...upstream

The ahead count will be the first number printed and the behind count will be the second.

like image 102
torek Avatar answered Oct 26 '25 18:10

torek