Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git: programmatically know by how much the branch is ahead/behind a remote branch

Tags:

git

git-status

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:

  1. How to know the remote tracked branch? It is often origin/branch but need not be.
  2. How to get the numbers? How to know whether it is ahead/behind? By how many commits? And what about the diverged branch case?
like image 323
Olivier Verdier Avatar asked Jun 03 '10 19:06

Olivier Verdier


People also ask

How can I tell if a remote branch is advance?

First use git remote update , to bring your remote refs up to date. Then you can do one of several things, such as: git status -uno will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.

How do you check if branch is behind?

You can do this with a combination of git merge-base and git rev-parse . If git merge-base <branch> <remote branch> returns the same as git rev-parse <remote branch> , then your local branch is ahead. If it returns the same as git rev-parse <branch> , then your local branch is behind.

How do you check if git branch is up to date with remote?

To check if you're up-to-date with GitHub run git fetch origin before git status and you'll know you're up-to-date.

What is the git command to view all the remote branches git branch git view remote branch none of the options git branch?

To see all local and remote branches, run this command: git branch -a.


1 Answers

git rev-list origin..HEAD will show the commits that are in your current branch, but not origin -- i.e., whether you're ahead of origin and by which commits.

git rev-list HEAD..origin will show the opposite.

If both commands show commits, then you have diverged branches.

like image 120
jamessan Avatar answered Sep 28 '22 23:09

jamessan