brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: git rev-list with left-right and count tells you how far ahead or behind you are

Git
~/tips/tip-git-rev-list-ahead-behind

git rev-list --left-right --count main...HEAD

Prints two numbers: commits only on one branch and commits only on the other.

git status only tells you how far ahead or behind you are compared with the upstream branch. For any two branches, ask git rev-list.

git rev-list --left-right --count main...HEAD

The output is two numbers separated by a tab, like 5 3. The left number counts commits that are only on main, the right number commits only on HEAD. So here the branch is 3 commits ahead of main and 5 behind. The three dots are important: they mean “on either side but not on both”, and --left-right keeps the two sides apart.

Because it’s just numbers, it’s nice in scripts and prompts. To warn before a release when a branch has fallen behind:

behind=$(git rev-list --left-right --count main...HEAD | cut -f1)
[ "$behind" -gt 0 ] && echo "main has $behind new commits"

It works for remote branches too. Fetch first, then compare with origin/main...HEAD.

The numbers count commits, not how hard a merge will be. One commit behind can be a huge refactor, fifty can be typo fixes. And without a fresh git fetch, the remote side is only as current as your last fetch, which is the mistake I’d make most with this.

Further reading: git-rev-list documentation

More Git tips git show-branch main feature git log --stat -5 git merge --no-ff feature -m "Merge feature" git merge --squash feature git merge --abort All Git tips (144) All topics

Link