我在~/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?


当前回答

主要有两种解决方案:

You need to specify the branch name with -b command switch. Here is the syntax of the command to clone the specific git branch. git clone -b <BRANCH_NAME> <GIT_REMOTE_URL> Example: git clone -b tahir https://github.com/Repository/Project.git The following command will clone the branch tahir from the git repository.The above command clones only the specific branch but fetches the details of other branches. You can view all branches details with command. git branch -a You can use --single-branch flag to prevent fetching details of other branches like below: git clone -b <BRANCH_NAME> --single-branch <GIT_REMOTE_URL> Example: git clone -b tahir --single-branch \ https://github.com/Repository/Project.git Now if you do a git branch -a, it will only show your current single branch that you have cloned and not all the branches. So it depends on you how you want it.

其他回答

使用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

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

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

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

你可以使用下面的命令:

git clone -b branch_name --single-branch project_url local_folder_to_clone_in

你可以试试长篇大论的方式:

mkdir newrepo.git
cd newrepo.git
git init
git remote add origin file:///path/to/original
git fetch origin branchiwant:refs/remotes/origin/branchiwant
git checkout -b branchiwant --track origin/branchiwant

它的作用是:

创建并初始化一个空Git存储库。 将原始存储库添加为名为origin的远程存储库。 只从称为origin的远端获取所需的分支。 创建并签出一个新分支,该分支被设置为跟踪刚刚克隆的源分支。

希望这是你所追求的东西。

对于像我这样的新手来说, 只需运行下面的代码

git clone https://gitlab.com/repo/repo.git --branch <name of branch> --single-branch