How can I check if a git branch has a tracking branch?

I am writing a little git helper for bash and I need to know if a branch of any name has a tracking branch or not.

In particular, the problem is that if you run git pull

on a branch that does not have a tracking branch, it will fail with the following:

There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details

git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

git branch --set-upstream-to=origin/<branch> foo


git pull --quiet

also does not suppress this message.

I managed to find this useful shortcut:

git rev-parse --symbolic --abbrev-ref foo@{u}


It does exactly what I want and outputs the following if a tracking branch is present:



But if the branch doesn't have a tracking branch, here's the output:

fatal: No upstream configured for branch 'foo'


This is pretty good, except that it exists with a non-zero status and outputs it to stderr.

So what I basically want to do is:

tracking_branch=$(git do-some-magick foo)
if [[ -n $tracking_branch ]]; then
    git pull


Instead of this:

tracking_branch=$(git rev-parse --symbolic --abbrev-ref foo@{u} 2> /dev/null)
if [[ -n $tracking_branch ]]; then
    git pull


Actually it works fine, but it doesn't seem correct to me. Are there any other ways to do this?


source to share

1 answer

You can try this to find the tracking thread:

git config --get



$ git config --get branch.master.merge

$ git config --get # <- nothing printed for non-tracked branch "foo"


Tracking branch information is stored in the repository .git/config

, according to the git pull guide :

The default values ​​for <repository> and <branch> are read from the "remote" and "merge" configuration for the current branch, as set by git -branch [1] --track.



All Articles