没有分离头的开关分支

我在 github 上有一个存储库,其中有一个主分支(master)和一个用于某些实验工作的分支。我做了一些提交,并推到实验分支,一切都很好。

现在,在另一台机器上,我尝试克隆我的存储库(git 克隆 储存库) ,然后切换到实验分支(git checkout 分支名称) ,但是每次我这样做时,我的大脑就会分离,无法推动我的更改。我做错了什么?我觉得自己似乎遗漏了一些基本的 git 概念,但是阅读随机的 git 手册页并没有给我任何线索。

我是新来的,所以我很抱歉,如果我是一个白痴,但我不能找到任何东西,在文件,可以帮助我重新接上我的头。

剪辑

追踪分支的概念正是我所缺少的。现在我明白了这个概念,一切都清楚了。就我个人而言,我发现 git branch --track语法比 git checkout -b branch-name origin/branch-name更加直观。

谢谢你的帮助!

46178 次浏览
# first time: make origin/branchname locally available as localname
git checkout -b localname origin/branchname


# othertimes
git checkout localname


git push origin

For convenience, you may use the same string for localname & branchname
When you checked out origin/branchname you weren't really checking out a branch. origin/branchname is a "remote" name, and you can get a list of them with

branch -a

If you have colours enabled, local branches will be one colour, and remote another.

You have to first make a remote branch tracked locally in order to be able to switch-to and work on it.

git clone git@github.com:abc/def.git
cd def

Now create a tracking branch:

git branch --track experimental origin/experimental
git checkout experimental

Then, after working there, simply push to github by

git push

To expand on Kent's reply, after you do your clone the only branch you'll have (remotes don't count) is the one that was active in the repository you cloned from -- master in your case.

So, first you'll want to create a new branch to track the remote experimental branch:

$ git branch experimental origin/experimental

and then check it out:

$ git checkout experimental

However, Kent is correct -- these two commands can be combined

$ git checkout -b experimental origin/experimental

With Git 2.23 (August 2019), you would use the git switch command

If you have a remote branch of the same name, it will be automatically tracked:

$ git switch new-topic
Branch 'new-topic' set up to track remote branch 'new-topic' from 'origin'
Switched to a new branch 'new-topic'