2

I am trying to clone multiple specific branches in a repository.

I know it is possible to clone one specific branch using --single-branch, but what if I want 2 specific branches and no other branch?

I know I can use git config remote.origin.fetch as shown here to change the regex of the "monitored" branches, but can I do this when I clone?

Joundill
  • 6,828
  • 12
  • 36
  • 50
Tomer Amir
  • 1,515
  • 4
  • 27
  • 54

2 Answers2

4

You cannot do this with git clone directly, but you don't need to.

Remember that git clone is short for doing git init, git remote add, git fetch, and git checkout (more precisely there are six steps but this is the gist). The git remote add command itself can add multiple single branches, while git clone cannot.

Hence, the two ways to go are:

  • split out the commands needed so that you can run git remote add yourself
  • or, probably easier, do a single-branch clone, then git remote set-branches origin each of the remaining branches (one per command or all at once).

If you use the git remote set-branches method, remember to run git fetch again afterward.

torek
  • 448,244
  • 59
  • 642
  • 775
  • For those like me that saw `git remote set-branches ` and thought "hell yes I can use this for my one-off branch fetch": note that this will reset your refspec until you reset it. To go back to fetching all branches, you need to use `git remote set-branches '*'` (see https://stackoverflow.com/a/47726250/2752888) – ZNK Aug 12 '21 at 14:57
  • 1
    @ZNK: right - for a one-off, it's better to run `git fetch ` with an explicit refspec. You can use a remote name, or a raw URL, for the `` part; if you use a URL, Git can't update any remote-tracking names (though a sort-of-bug in `git push -u` will sometimes appear to claim otherwise). – torek Aug 12 '21 at 19:33
  • when i add some branches with `git remote set-branches --add origin branch1 branch2` then `git fetch origin` will still fetch all branches. currently im using `git fetch origin branch1 branch2` to fetch only some branches – milahu Aug 06 '23 at 11:53
0

If you are trying to clone multiple specific branches from a different repository, what you can do is, firstly, to change your current repository remote by git remote remove. And then replace it with the target repository where your two branches sit by: git remote add origin <new-repository-name>. Secondly, run git fetch, which will retrieve all branches and updates, and after that, run git checkout <branch> for each of the two branches, which will create a local copy of the branches. All that's left now is to get the previous remote back for your repository in the way described above. This worked for me!

Maksym Dudyk
  • 1,082
  • 14
  • 16