假设有一个远程 git 仓库的克隆版本,它与我的本地仓库是从同一个仓库克隆的,并且在那个远程克隆版本中存在一个不在我的克隆版本中的分支(不是默认分支)。
有没有办法将该远程分支克隆到我的本地副本?我不想将其与当前分支合并或做任何其他操作,我只想启动该远程分支的本地副本。是否有方法可以实现这一点?
完成此操作后,我还想知道如何将该分支添加到默认的远程副本中,以便我的本地克隆版本默认检查该分支。
您需要运行以下命令:
# Fetch everything from the other remote
git fetch <remote name>
# Check out the remote version of the branch
git checkout <remote name>/<branch name>
# Create the new local branch
git checkout -b <branch name>
这会给你一个本地的、可行的分支副本。然后,要将其推送回原始远程仓库(假设它是origin
),我们只需运行:
git push origin <branch name>:<branch name>
只需使用next:
git fetch <remote repo name>
git checkout -b <local branch name> <remote repo name>/<remote branch name>
一个命令即可完成此工作:
git checkout -b <local_branch_name> origin/<remote_branch_name>
git pull
git checkout -b <local_branch_name> origin/<remote_branch_name>
从Git版本2.37.2开始,您现在可以按照以下步骤使用$ git switch -c
。
$ git fetch <remote>
$ git checkout <remote>/<branch>
$ git switch -c <branch>
git remote add <name> <url>
命令添加远程仓库名称和 URL,然后使用提供的远程仓库名称进行获取操作。这样你以后就可以轻松地从该仓库获取最新的更改了。如果你不想这样做,可以使用git fetch <remote> <branch>
命令获取代码,然后使用git checkout FETCH_HEAD
命令切换到该分支,但你需要知道另一个远程仓库上分支的名称。 - afontaine