Git compare branch commits

Given you have a local Git repository with the following branches:

$ git branch
* master

To see the commit messages that are on master but not on myBranch:

git log master ^myBranch

To see the commit messages (first line) that are on myBranch but not on master:

git log --oneline myBranch ^master

To count how many commits your branch is ahead of master:

git log --oneline $(git rev-parse --abbrev-ref HEAD) ^master | wc -l

Note: git rev-parse --abbrev-ref HEAD returns the name of the branch you’re currently on.

You can also format the data into a useful message:

COUNT_AHEAD=$(git log --oneline $(git rev-parse --abbrev-ref HEAD) ^master | wc -l | xargs)
COUNT_BEHIND=$(git log --oneline master ^$(git rev-parse --abbrev-ref HEAD) | wc -l | xargs)
echo "$COUNT_AHEAD commits ahead and $COUNT_BEHIND commits behind master"

Note: wc -l outputs the line count and xargs trims the whitespace.

Example output:

13 commits ahead and 37 commits behind master

Please support this site and join our Discord!