让现有的 git 分支跟踪远程分支

在使用 git 时,我通常的工作流程是这样的:

  1. 创建一个本地存储库
  2. 在存储库中做一些工作,添加/更改文件等。
  3. 决定我需要一个中心远程位置为存储库,并创建一个
  4. 将所有提交从本地存储库推送到这个新的远程存储库

但是,现在我希望能够从这个远程存储库访问 pushpull,而不必指定从哪里进行推送或拉取; 我希望我的本地主机跟踪远程主机。

我不清楚 适当的的方法,我无法从文档中确定它,即使它实际上不应该超过一个命令。

因为每个存储库只做一次,所以我通常采用两种简单但蹩脚的解决方案中的一种:

  1. 使用 git clone制作了一个新的本地存储库,并删除了旧的。在 git 克隆之后,将设置新的存储库来跟踪源。
  2. 手动编辑. git/config,使主跟踪原点。

我认为我应该能够运行一个命令,可能是某种形式的 git remote来设置一个现有的存储库,让主跟踪一个远程主机。有人能告诉我这是什么指令吗?

87953 次浏览

git help remote should show you what you need to know. I think what you want is

git remote add [remote-name] [remote-url]


# Set a local branch to follow the remote
git config branch.[branch-name].remote [remote-name]


# Set it to automatically merge with a specific remote branch when you pull
git config branch.[branch-name].merge [remote-master]

You can also manually edit .git/config to set these up.

You can also use this if you want to create a new local branch to track a remote branch:

git checkout --track -b [branch_name] --track origin[or other remote name]/[remote_branch_name]

or even better:

git checkout -t origin/branch_name

Use the set-upstream arg:

git branch --set-upstream local-branch-name origin/remote-branch-name

Running the above command updates your .git/config file correctly and even verifies with this output:

"Branch local-branch-name set up to track remote branch remote-branch-name from origin."

EDIT: As martijn said: "In version Git v1.8.0, --set-upstream is deprecated. Use --set-upstream-to instead."

git branch --set-upstream-to local-branch-name origin/remote-branch-name

See this for more information.

On newer versions of git you can use

git branch --track origin/branch_name

The --set-upstream flag is deprecated and will be removed.

git branch master --set-upstream-to myupstream/master

Fast forward three years (see what I did there :-) ), I tried to pull an untracked branch using Git Bash and received

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

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

The following achieved what I needed:

$ git branch --set-upstream-to=origin/develop develop Branch 'develop' set up to track remote branch 'develop' from 'origin'.

Use this command:

git clone [<options>] [--] <repo> [<dir>]