You can clone a specific branch from a Git repository using the git clone –single-branch –branch command. This command retrieves all the files and metadata associated with one branch. To retrieve other branches, you'll need to fetch them later on.
There are two ways to clone a specific branch. You can either: Clone the repository, fetch all branches, and checkout to a specific branch immediately. Clone the repository and fetch only a single branch.
git clone downloads all remote branches but still considers them "remote", even though the files are located in your new repository. There's one exception to this, which is that the cloning process creates a local branch called "master" from the remote branch called "master".
You can tell Git to pull all branches like this:
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
git fetch origin
If you look in .git/config
, it'll look something like this:
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = false
[remote "origin"]
url = https://github.com/owner/repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
rebase = true
I compared this to a full clone, and saw that the only difference was the "fetch" under [remote "origin"]
.
Note: I'm running Git version 1.8.2. The config options may have changed if you're running an older version of Git. If my commands don't work, then I'd recommend looking through .git/config
to see if you can see something similar.
If you want to add a single branch, you can do the following:
git remote set-branches --add origin [remote-branch]
git fetch origin [remote-branch]:[local-branch]
Works with git version 1.9.1
To add another remote branch to my local repository that was cloned using --single-branch
, the following works for me:
git remote set-branches --add origin [remote-branch]
git fetch
git checkout [remote-branch]
You can also use wildcards for [remote-branch]
, e.g.
git remote set-branches --add origin release-1.*
git fetch
git checkout release-1.5
This works using git version 2.21.1. Other answers suggesting to do git fetch origin [remote-branch]:[local-branch]
did not work as it creates the local branch in an untracked state. When running git pull
it first tried to merge all the commits of the remote branch to my local one once again.
For me worked:
git remote remove origin
git remote add origin https://*<yourPath>*.git
git fetch
Just add the original repo as a new remote, and work off of there?
git remote add path/to/myrepo myNewOrigin
git fetch myNewOrigin
You can even delete your current 'origin' remote and rename 'myNewOrigin' to 'origin' if you would want to.
From there you can pull/merge/rebase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With