检出一个本地不存在的远程git分支?

10
假设有一个远程 git 仓库的克隆版本,它与我的本地仓库是从同一个仓库克隆的,并且在那个远程克隆版本中存在一个不在我的克隆版本中的分支(不是默认分支)。

有没有办法将该远程分支克隆到我的本地副本?我不想将其与当前分支合并或做任何其他操作,我只想启动该远程分支的本地副本。是否有方法可以实现这一点?

完成此操作后,我还想知道如何将该分支添加到默认的远程副本中,以便我的本地克隆版本默认检查该分支。

4个回答

7

您需要运行以下命令:

# 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>

这将把你的新分支推送到原始远程仓库。

我不确定我理解了。在你的指示中有一些我不明白的地方。如果你看一下这个pastebin http://pastebin.com/kujnaY9e,也许你可以告诉我我做错了什么,或者我在你的建议中误解了什么。 - Sophia_ES
啊,好的。首先使用 git remote add <name> <url> 命令添加远程仓库名称和 URL,然后使用提供的远程仓库名称进行获取操作。这样你以后就可以轻松地从该仓库获取最新的更改了。如果你不想这样做,可以使用 git fetch <remote> <branch> 命令获取代码,然后使用 git checkout FETCH_HEAD 命令切换到该分支,但你需要知道另一个远程仓库上分支的名称。 - afontaine

3

只需使用next:

git fetch <remote repo name>
git checkout -b <local branch name> <remote repo name>/<remote branch name>

这对我的情况很有帮助,这个过程与我在Windows机器上通过TortoiseGit自动生成的操作完全相同。

git fetch 是否总是必需的? - Konrad Viltersten
@KonradViltersten 是的 - Paul Basenko

3

一个命令即可完成此工作:

git checkout -b <local_branch_name> origin/<remote_branch_name>

编辑: 如果出现错误: fatal: 'origin/' 不是一个提交,无法从中创建分支 ''。
您可以尝试:
git pull
git checkout -b <local_branch_name> origin/<remote_branch_name>

0

从Git版本2.37.2开始,您现在可以按照以下步骤使用$ git switch -c

从远程仓库获取所有内容。

$ git fetch <remote>

检出远程分支

$ git checkout <remote>/<branch>

创建新的本地分支

$ git switch -c <branch>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接