我在~/local_repo有一个本地Git存储库。它有几个分支:

$ git branch
* master
  rails
  c
  c++

要克隆本地存储库,我做:

$ git clone ~/local_repo new_repo
Initialized empty Git repository in /home/username/new_repo/.git/

new_repo master分支指向local_repo master分支,我可以推/拉。

但我无法克隆另一个分支。我只想拉我想要的分支(例如rails),这样新的存储库就有一个主分支,默认情况下,它可以推入和拉出local_repo的rails分支。我如何实现这一点,或者也许类似于local_repo跟踪主local_repo?


当前回答

一种方法是执行以下操作。

git clone user@git-server:project_name.git -b branch_name /your/folder

其中branch_name是您选择的分支,“/your/folder”是该分支的目标文件夹。这确实会带来其他分支,让你有机会来回合并。

更新

现在,从Git 1.7.10开始,您就可以这样做了

git clone user@git-server:project_name.git -b branch_name --single-branch /your/folder

其他回答

类似于@nosaiba-darwish在这里说的:这里

我们公司通常是这样做的:

git clone -b <name_of_branch> --single-branch <git_url> folder_to_clone_locally

使用Github CLI

如果您正在使用Github CLI克隆一个回购,克隆选项必须声明不同。

——深度= 1

gh repo clone username/repo -- --depth=1

——单个的分支

gh repo clone username/repo -- --single-branch

——分支

gh repo clone username/repo -- --branch main --single-branch localDir

让我们以flask repo为例。除master外,它还有3个分支。让我们签出1.1。X远程分支

克隆git回购

git clone https://github.com/pallets/flask

CD进入回购。

cd flask

获取远程分支1.1.x

git fetch origin 1.1.x

签出分支

git checkout 1.1.x

您将切换到分支1.1。X,它将跟踪远程1.1。x分支。

git clone --branch {branch-name} {repo-URI}

例子:

git clone --branch dev https://github.com/ann/cleaningmachine.git

dev:这是{branch-name} https://github.com/ann/cleaningmachine.git:这是{repo-URI}

如果你想要一个浅克隆,你可以这样做:

git clone -b mybranch --depth=1 https://example.com/myproject.git localname

——depth=1表示——single-branch。