远程存储库包含各种分支,如origin/davis_branch:

$ git branch -r
origin/HEAD -> origin/master
origin/daves_branch
origin/master

如何将daves_branch获取到本地存储库,以便它跟踪origin/davis_branch?

我尝试了:

$ git fetch origin discover
$ git checkout discover

当前回答

在我看来,这一行命令是获取和签出本地不存在的远程分支的最简单方法:git获取和git签出remote_branch

其他回答

如果您有一个使用--depth 1克隆的存储库,那么列出的许多命令将无法工作。例如,请参见此处

% git clone --depth 1 https://github.com/repo/code
Cloning into 'code'...
cd code
remote: Counting objects: 1778, done.
remote: Compressing objects: 100% (1105/1105), done.
remote: Total 1778 (delta 87), reused 1390 (delta 58), pack-reused 0
Receiving objects: 100% (1778/1778), 5.54 MiB | 4.33 MiB/s, done.
Resolving deltas: 100% (87/87), done.
Checking connectivity... done.
Checking out files: 100% (1215/1215), done.
% cd code
% git checkout other_branch
error: pathspec 'other_branch' did not match any file(s) known to git.
% git fetch origin other_branch
remote: Counting objects: 47289, done.
remote: Compressing objects: 100% (15906/15906), done.
remote: Total 47289 (delta 30151), reused 46699 (delta 29570), pack-reused 0
Receiving objects: 100% (47289/47289), 31.03 MiB | 5.70 MiB/s, done.
Resolving deltas: 100% (30151/30151), completed with 362 local objects.
From https://github.com/repo/code
 * branch            other_branch-> FETCH_HEAD
% git checkout other_branch
error: pathspec 'other_branch' did not match any file(s) known to git.
%

在这种情况下,我会重新克隆存储库,但可能还有其他技术,例如git浅层克隆(clone--depth)错过了远程分支

本地获取分支:

git fetch origin <branchName>

移动到该分支:

git checkout <branchName>

使用gitbranch-a(本地和远程分支)或gitbranch-r(仅远程分支)查看所有远程及其分支。然后,您可以对远程执行git checkout-t remotes/repo/branch并创建本地分支。

还有一个git-ls-remote命令,用于查看该远程的所有ref和标记。

更新:使用Git Switch

下面写的所有信息都是准确的,但添加了一个新命令gitswitch,简化了工作。

如果daves_branch存在于远程存储库中,但不存在于本地分支中,则只需键入:

git switch daves_branch

由于您在本地没有分支,这将自动使交换机在远程回购上运行。然后,它还将自动设置远程分支跟踪。

请注意,如果daves_branch在本地不存在,则在使用开关之前需要先获取git。


原始帖子

您需要创建跟踪远程分支的本地分支。以下命令将创建一个名为daves_branch的本地分支,跟踪远程分支origin/davis_branch。当您推送更改时,远程分支将被更新。

对于最新版本的Git:

git checkout --track origin/daves_branch

--track是git checkout的简写-b[branch][remotename]/[branch],在本例中[remotename]是原点,[branch是两倍,在本示例中是davesbranch。

对于Git 1.5.6.5,您需要:

git checkout --track -b daves_branch origin/daves_branch

对于Git 1.7.2.3及更高版本,这已经足够了(它可能更早开始,但这是我可以很快找到的最早确认):

git checkout daves_branch

注意,对于最新的Git版本,此命令不会创建本地分支,并将使您处于“分离HEAD”状态。如果需要本地分支,请使用--track选项。

详细信息如下:3.5 Git分支-远程分支,跟踪分支

git fetch--all&git checkout<分支名称>