I would like to extract the information that is printed after a git status, which looks like:
# On branch master
# Your branch is ahead of 'origin/master' by 2 commits.
Of course I can parse the output of git status but this is not recommended since this human readable output is liable to change.
There are two problems:
- How to know the remote tracked branch? It is often
origin/branchbut need not be. - How to get the numbers? How to know whether it is ahead/behind? By how many commits? And what about the diverged branch case?
update
As pointed out by amalloy, recent versions of git support finding the matching tracking branch for a given branch by giving “branchname@{upstream}” (or “branchname@{u}”, or “@{u}” for the tracking branch of HEAD). This effectively supercedes the script below. You can do:
etc. For example, I have
git qaliased togit log --pretty='...' @{u}..to show me “queued” commits ready for pushing.original answer
There doesn’t seem to be an easy way to find the tracking branch in general, without parsing lots more git config than is practical in a few shell commands. But for many cases this will go a long way:
Another, more brute-force, approach:
jamessan’s answer explains how to find the relative differences between $tracking_branch and HEAD using
git rev-list. One fun thing you can do:(note three dots between $tracking_branch and HEAD). This will show commits on both “arms” with a distinguishing mark at the front: “<” for commits on $tracking_branch, and “>” for commits on HEAD.