git ahead/behind info between master and branch?

Part 1

As an answer on your question 1, here’s a trick I found to compare two branches and show how many commits each branch is ahead of the other (a more general answer on your question 1):

For local branches:
git rev-list --left-right --count master...test-branch

For remote branches:
git rev-list --left-right --count origin/master...origin/test-branch

This gives output like the following:

2 1

This output means: “Compared to master, test-branch is 1 commit ahead and 2 commits behind.”

You can also compare local branches with remote branches, e.g. origin/master...master to find out how many commits a local branch (here master) is ahead/behind its remote counterpart.

Part 2

To answer the second part of your question, the solution depends on what exactly you want to achieve.

To view commits

In order to have git rev-list return the exact list of commits unique on either side, replace the --count argument with something like --pretty=oneline, making the complete command to execute:

git rev-list --left-right --pretty=oneline master...test-branch

This will generate output like this:

<bba27b56ad7072e281d529d4845e4edf877eb7d7 unique commit 2 on master
<dad0b69ec50ea57b076bfecabf2cc7c8a652bb6f unique commit 1 on master
>4bfad52fbcf0e60d78d06661d5c06b59c98ac8fd unique commit 1 on test-branch

Here every commit sha is preceded by < or > to indicate which branch it can be found on (left or right, here master or test-branch respectively).

To view code

If you want to view a diff of all new commits only found on either branch, you’ll need to do this in two steps:

  1. define the most recent common ancestor
$ git merge-base master test-branch
c22faff7468d6d5caef217ac6b82f3ed95e9d902
  1. diff either branch to the commit sha obtained above (short format will usually do)

To show the diff of all commits only found on master

git diff c22faff7..master

To show the diff of all commits only found test-branch

git diff c22faff7..test-branch

Leave a Comment