How to change the remote a branch is tracking?

2019-01-02 16:11发布

The central repository had to be set up on a new server, so I created a new remote on my local repo, and pushed to that.

But now when I do git pull, it claims I am up to date. It's wrong—it's telling me about the old remote branch, not the new one, which I know for a fact has new commits to fetch.

How do I change my local branch to track a different remote?

I can see this in the git config file but I don't want to mess things up.

[branch "master"]
    remote = oldserver
    merge = refs/heads/master

标签: git
10条回答
倾城一夜雪
2楼-- · 2019-01-02 16:46

If you're sane about it, editing the config file's safe enough. If you want to be a little more paranoid, you can use the porcelain command to modify it:

git config branch.master.remote newserver

Of course, if you look at the config before and after, you'll see that it did exactly what you were going to do.

But in your individual case, what I'd do is:

git remote rename origin old-origin
git remote rename new-origin origin

That is, if the new server is going to be the canonical remote, why not call it origin as if you'd originally cloned from it?

查看更多
公子世无双
3楼-- · 2019-01-02 16:48

You could either delete your current branch and do:

git branch --track local_branch remote_branch

Or change change remote server to the current one in the config

查看更多
妖精总统
4楼-- · 2019-01-02 16:50

In latest git version like 2.7.4,

git checkout branch_name #branch name which you want to change tracking branch

git branch --set-upstream-to=upstream/tracking_branch_name #upstream - remote name

查看更多
美炸的是我
5楼-- · 2019-01-02 16:51

Based on what I understand from the latest git documentation, the synopsis is:

git branch -u upstream-branch local-branch
git branch --set-upstream-to=upstream-branch local-branch

This usage seems to be a bit different than urschrei's answer, as in his the synopsis is:

git branch local-branch -u upstream-branch 
git branch local-branch --set-upstream-to=upstream-branch 

I'm guessing they changed the documentation again?

查看更多
临风纵饮
6楼-- · 2019-01-02 16:53

Another option to have a lot of control over what's happening is to edit your configurations by hand:

git config --edit

or the shorthand

git config -e

Then edit the file at will, save and your modifications will be applied.

查看更多
孤独寂梦人
7楼-- · 2019-01-02 16:55

Using git v1.8.0 or later:

git branch branch_name --set-upstream-to your_new_remote/branch_name

Or you can use the -u switch:

git branch branch_name -u your_new_remote/branch_name

Using git v1.7.12 or earlier:

git branch --set-upstream branch_name your_new_remote/branch_name

查看更多
登录 后发表回答