Check If Local Branch Exists On Remote Git
To check if your local branch has changes vs. the upstream tracking branch, you can run:
git diff @{u}
Where @{u}
refers to the upstream branch name. From the git-rev-parse(1)
man page:
@{upstream}, e.g. master@{upstream}, @{u}
The suffix @{upstream} to a branchname (short form @{u}) refers to the branch that the branch specified by branchname is set to build on top of (configured with branch..remote and branch..merge). A missing branchname defaults to the current one.
This will output typical git diff
output showing changes between your local branch and the upstream tracking branch. If you want to use this as part of a shell command (e.g., for setting your prompt or something), you can add --quiet
:
git diff --quiet @{u}
This will return a non-zero exit code if there are differences. E.g.:
git diff --quiet @{u} || echo "You need to push your changes!"
git fetch origin
git branch -r --contains $mybranch
and if you're sure any pushes came from this particular repo you can omit the fetch.
Inside your local git folder, you can do
git checkout
If there is no corresponding remote branch, there is no output. Otherwise it will print out the relationship between the local and remote branch (ahead, behind, diverged, etc)
Note: this doesn't work for 1.8.3.1, but works for 2.16.2
I actually wrote a small tool to see the status of all my repos. You can find it on github. If the color of the branch is shown as white, it means there is no remote branch.
- white: local has no remote
- green: local is the same as remote
- red: local has diverged from remote
- purple: local is ahead of remote (good for push)
- yellow: local is behind remote (good for merge)
This will set exit code to 2 if current branch does not exist on remote:
git ls-remote --heads --exit-code origin "$(git symbolic-ref --short HEAD)"
Then you can check in shell:
if [ $? -eq 2 ]
Or in ruby:
if $?.exitstatus == 2
Or similarly in any other language.