How to list branches in git with the number of commits ahead or behind master?
Asked Answered
M

2

6

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

Micronesian answered 20/11, 2020 at 22:28 Comment(4)
Does this answer your question? git ahead/behind info between master and branch?Deportment
@Deportment kind of, that works for a single branch, but how would I list all branches with the commits ahead/behind count?Micronesian
You can fetch all branches and then get the information for each branch.Deportment
@Deportment 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.Micronesian
Y
7
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

Yasmin answered 20/11, 2020 at 23:12 Comment(2)
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 fileMicronesian
I think due to the amount of code and its complexity it is better to write a shell script, not git alias.Yasmin
M
0

I needed something like this as an alias, so converted it is:

alias gitbs='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'
Milquetoast answered 24/10, 2024 at 8:41 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.