我在GitHub上有一个项目。我在一台电脑上创建了一个分支,然后使用以下命令将更改推送到GitHub:
git push origin branch-name
现在我在另一台电脑上,想要下载那个分支。所以我尝试了:
git pull origin branch-name
...但这只是用新分支的更改覆盖了我的主分支。
我需要怎么做才能正确地拉取我的远程分支,而不会覆盖现有的分支?
感谢相关问题,我发现我需要将远程分支作为新的本地分支进行“checkout”,并指定一个新的本地分支名称。
git checkout -b newlocalbranchname origin/branch-name
或者您可以这样做:
git checkout -t origin/branch-name
更新:自我最初发布这个问题以来已经过去了5年。我学到了很多,git也有所改进。我的常规工作流现在有点不同。
如果我想获取远程分支,我只需运行:
git pull
From github.com:andrewhavens/example-project
dbd07ad..4316d29 master -> origin/master
* [new branch] production -> origin/production
* [new branch] my-bugfix-branch -> origin/my-bugfix-branch
First, rewinding head to replay your work on top of it...
Fast-forwarded master to 4316d296c55ac2e13992a22161fc327944bcf5b8.
现在git已经知道了我的新的my-bugfix-branch
。要切换到这个分支,我可以简单地运行以下命令:
git checkout my-bugfix-branch
通常情况下,在检出之前,我需要先创建分支,但在较新版本的Git中,它足够智能,知道您想要检出此远程分支的本地副本。
对于像我这样的 Git 新手,以下是一些步骤,您可以按照这些步骤下载远程仓库并切换到您想要查看的特定分支。它们可能会以某种方式滥用 Git,但对我来说完成了工作!:-)
克隆您想要下载代码的仓库(在此示例中,我选择了 Github 上的 LRResty 项目):
$ git clone https://github.com/lukeredpath/LRResty.git
$ cd LRResty
检查当前所使用的分支(应该是主分支):
$ git branch
* master
检查你想要的分支,对我来说它被称为“arcified”:
$ git checkout -b arcified origin/arcified
Branch arcified set up to track remote branch arcified from origin.
Switched to a new branch 'arcified'
确认你现在正在使用你想要的分支:
$ git branch
* arcified
master
如果您想稍后再次更新代码,请运行git pull
:$ git pull
Already up-to-date.
您可以使用:
git clone <url> --branch <branch>
来克隆/下载分支的内容。
对我特别有帮助,因为我的分支内容与主分支完全不同(虽然这通常不是这种情况)。因此,其他人上面列出的建议对我没有帮助,即使我检出了分支并执行了 git pull 命令,最终我还是得到了主分支的副本。
这个命令将直接给您提供分支的内容。这对我有效。
git fetch origin
然后设置一个本地分支来跟踪远程分支,如下所示:
git branch --track [local-branch-name] origin/remote-branch-name
现在您将拥有远程GitHub分支的内容,存储在本地分支名称中。
您可以切换到该本地分支名称,并开始工作:
git checkout [local-branch-name]
在你的新计算机上,打开Git Bash并导航到你想要从Git上下载的文件夹。
使用以下命令从任何分支下载代码:
git clone 'git ssh url' -b '分支名称'
它将下载相应的分支代码。
Git clone并进入仓库名称:
$ git clone https://github.com/PabloEzequiel/iOS-AppleWach.git
Cloning into 'iOS-AppleWach'...
$ cd iOS-AppleWach
切换到我想要的分支(一个 GitHub 页面):
$ git checkout -b gh-pages origin/gh-pages
Branch gh-pages set up to track remote branch gh-pages from origin.
Switched to a new branch 'gh-pages'
并拉取分支:
$ git pull
Already up-to-date.
ls:
$ ls
index.html params.json stylesheets
$ git fetch
$ git checkout <branch>
git fetch
将获取所有远程分支。你可以用 git branch -r
(或者 git branch -rv
) 命令来验证这些远程分支。如果没有同名的现有分支,那么可以直接使用 git checkout <branch>
命令切换到该分支。
https://github.com/[username]/[respository]/archive/refs/heads/[branch].zip
git checkout -b branch/name
创建一个新分支并切换到该分支。git pull origin branch/name
从远程仓库拉取指定分支的最新代码。git clone -b < branch name > <remote_repo url>
git branch --track XX origin/XX
。您的命令会导致错误。 - dimitarvp