Blog
Posted on: 31/01/2025

git, is branch behind or ahead of master?

GIT commands to count commits ahead or behind of master

Someone at work asked how they could check if their branch is ahead or behind of master. I was stumped by this as it never occurred to me how useful and sensible a functionality that is, even if I was using it subconsciously.

As I often use git rebase I've picked up some habits for better or worse. One of them is to regularly check how my work is coming along VS master, I do this by running:

git log --pretty=oneline --reverse --abbrev-commit master..

But it took my silly brain 🧠 a minute to figure out how that is literally checking for "commits ahead of master". Then it was a simple matter of connecting the dots

"master.." means ahead of master, ergo
"..master" means behind of master.

So the key commands one requires to solve the challenge are:

Commits ahead:git log --pretty=oneline master.. Commits behind:git log --pretty=oneline ..master

Now, as the handy --pretty=oneline option of git log gives 1 unique line per commit, we can easily pipe it for the counting 🤺:

Count commits ahead:git log --pretty=oneline master.. | wc -l Count commits behind:git log --pretty=oneline ..master | wc -l