简体   繁体   中英

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

I'm writing a small git helper for bash and I need to know whether the branch of some name has a tracking branch or not.

More specifically the problem is that if you run git pull on a branch which doesn't 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 doesn't suppress this message.

I've managed to find this useful shortcut:

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

It does exactly what I need, and outputs the following, if tracking branch is present:

origin/foo

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

fatal: No upstream configured for branch 'foo'

This is fairly ok, except that it exists with non-zero status, and outputs this to stderr.

So what I basically want to do is:

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

Instead of this:

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

It actually works fine, but doesn't seem right to me. Are there any other ways to do this?

You can try this to find the tracking branch:

git config --get branch.foo.merge

Examples:

$ git config --get branch.master.merge
refs/heads/master

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

The information about tracking branches are stored in repository specific .git/config , according to the manual for git pull :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM