5

I really like how the Github /branches page lists the branches and a column that indicates the number of commits ahead or behind master for a branch.

Is there a way to see this information in the console/cli?

Edit: This solution shows how to get the commits ahead/behind for a single branch. But how could I do that for all local branches?

enter image description here

Benjamin
  • 3,428
  • 1
  • 15
  • 25
  • 2
    Does this answer your question? [git ahead/behind info between master and branch?](https://stackoverflow.com/questions/20433867/git-ahead-behind-info-between-master-and-branch) – flaxel Nov 20 '20 at 22:35
  • @flaxel kind of, that works for a single branch, but how would I list all branches with the commits ahead/behind count? – Benjamin Nov 20 '20 at 22:48
  • You can [fetch all branches](https://stackoverflow.com/questions/10312521/how-to-fetch-all-git-branches) and then get the information for each branch. – flaxel Nov 20 '20 at 22:51
  • @flaxel yes, but I don't want to have to type a command for each branch. I'd like to issue a single command that lists all branches with the commit offsets. – Benjamin Nov 20 '20 at 22:54

1 Answers1

5
git for-each-ref refs/heads/ --format='%(refname:short)' |
while read branch; do
    echo -n "$branch: "
    git rev-list --left-right --count master..$branch
done

Docs:

https://git-scm.com/docs/git-for-each-ref

https://git-scm.com/docs/git-rev-list

phd
  • 82,685
  • 13
  • 120
  • 165
  • can you help me make this into a git alias? I tried `list = ! git for-each-ref refs/heads/ --format='%(refname:short)' | while read branch; do; echo -n "$branch: "; git rev-list --left-right --count master..$branch; done` But I get this error `$ git list` `git for-each-ref refs/heads/ --format='%(refname:short)' | while read branch: -c: line 1: syntax error: unexpected end of file` – Benjamin Nov 24 '20 at 05:27
  • I think due to the amount of code and its complexity it is better to write a shell script, not git alias. – phd Nov 24 '20 at 06:07