使用 Git 添加第二个远程源
有时,为了实现某些特殊功能,你需要为项目设置第二个远程源。对我来说,这意味着为网站添加自动部署功能,而我作为仓库所有者却无法访问源主仓库。
在这种情况下,我将从项目中获取一个副本,虽然它应该在每次更改时与原始主版本同步,但今天我们将看看如何实现这一点。
要向 Git 添加第二个远程源并将更改推送到 GitHub 上的两个存储库,您可以按照以下步骤操作:
- 打开终端或命令提示符,导航到要推送到两个存储库的本地 Git 存储库。
- 使用该
git remote -v命令列出仓库现有的远程源。您应该会看到类似这样的内容:
$ git remote -v
origin https://github.com/username/repo.git (fetch)
origin https://github.com/username/repo.git (push)
- 使用该
git remote add命令向仓库添加第二个远程源。例如,如果您想添加一个名为“second”的远程源,其 URL 为https://github.com/username/second-repo.git,则可以使用以下命令:
$ git remote add second https://github.com/username/second-repo.git
- 再次使用该
git remote -v命令确认已添加新的远程源:
$ git remote -v
origin https://github.com/username/repo.git (fetch)
origin https://github.com/username/repo.git (push)
second https://github.com/username/second-repo.git (fetch)
second https://github.com/username/second-repo.git (push)
-
对本地 Git 仓库进行任何更改,并使用
git commit命令提交更改。 -
使用该
git push命令将更改推送到两个远程源。要同时推送到两个远程源,可以使用以下--all选项:
$ git push --all
这将把所有分支推送到两个远程仓库。或者,您可以指定要推送到两个远程仓库的特定分支:
$ git push origin branch-name
$ git push second branch-name
这将把指定的分支推送到两个远程源。
同步两个远程源
要检查两个远程源是否同步,可以使用git fetch命令从两个源获取更改并进行比较。以下是具体操作方法:
- 使用 git fetch 命令从两个远程仓库获取更改:
$ git fetch origin
$ git fetch second
- 使用该
git log命令可以比较两个远程仓库的提交历史。例如,要比较两个仓库上的 master 分支,可以使用以下命令:
$ git log origin/master
& git log second/master
如果第二个源落后于第一个源,您可以通过从第一个源获取更改,然后将其推送到第二个源来同步它们。以下是具体操作方法:
- 从第一个源获取更改:
$ git fetch origin
- 将来自第一个源的更改合并到本地仓库中:
$ git merge origin/master
请注意,“origin/master”是您要从第一个源合并的分支的名称。请将“master”替换为您要合并的分支的名称。
- 将更改推送到第二个源:
$ git push second master
请注意,“second”是第二个远程仓库的名称,“master”是您要推送的分支的名称。请将“master”替换为您要推送的分支的名称。
就这样,
希望对你有帮助。
有任何问题请在评论区
留言。