Git远程仓库管理

前言

工作中有个别项目因为一些原因,需要需要在两个不同的代码仓库间提交、同步同一份代码, 这时,开发者可以通过在同一个本地git仓库中,关联不同的远程仓库来实现。

首先要确认的是,开发者同时拥有两个仓库的账号及操作权限,比如要操作的是两个不同gitlab的仓库,需要分别在gitlab账号中添加SSH Key。

使用git remote命令管理远程仓库

我们通过git remote相关的命令来管理需要关联的远程仓库。

查看远程仓库

查看所有远程仓库的别名:

bash 复制代码
$ git remote
origin

使用这个命令会列出所有远程仓库的简短别名,我们使用git clone命令克隆一个仓库时,git会默认给它命名为origin。

查看所有远程仓库的别名及地址等详细信息:

bash 复制代码
$ git remote -v
origin	ssh://[email protected]/git-demo.git (fetch)
origin	ssh://[email protected]/git-demo.git (push)

加上-v参数后,会列出别名及地址详细信息,表示我们拥有对应远程仓库的拉取、推送权限。

另外,所有远程仓库信息被保存在本地文件.git/config中。

添加远程仓库

bash 复制代码
$ git remote add <name> <url>

重命名

bash 复制代码
$ git remoet rename <old-name> <new-name>

删除远程仓库

bash 复制代码
$ git remove <name>
$ git rm <name>

对指定远程仓库的git操作

获取远程分支:

bash 复制代码
$ git fetch <remote-name> <branch-name>

检出远程分支到本地:

bash 复制代码
$ git checkout -b <local-branch-name> <remote-name>/<remote-branch-name>

git add, git commit之后推送代码到远程分支

bash 复制代码
$ git push -u <remote-name> <branch-name>
bash 复制代码
$ git merge <branch-name>

可能遇到的问题

合并两个不同远程仓库的分支时,可能会出现错误提示:

bash 复制代码
$ git merge <branch>
fatal: 拒绝合并无关的历史

通过添加--allow-unrelated-histories来解决:

bash 复制代码
$ git merge <branch> --allow-unrelated-histories 

本地分支名与远程分支名不同时,有可能错误操作推送产生新的分支,可以使用以下命令删除不需要的远程分支:

bash 复制代码
$ git push origin -d "branch-name"

总结一下

要将一个本地仓库代码同步至多个不同的远程仓库,可以通过在本地关联多个不同的远程仓库来实现。

  • 确保同时拥有两个仓库的操作权限
  • 在已有的仓库中,添加新的remotegit remote add <new-remote-name>
  • 拉取新remote分支git pull <new-remote-name> <branch-name>
  • 提交、推送代码至新remotegit push <new-remote-name> <branch-name>
相关推荐
西瓜本瓜@2 小时前
在Android中如何使用Protobuf上传协议
android·java·开发语言·git·学习·android-studio
4Forsee5 小时前
【Git】从本地存档到协作开发的Git简单使用
git
Э时间行者于我7 小时前
git同时删除多个分支
git
我的golang之路果然有问题14 小时前
给git配置SSH(github,gitee)
经验分享·笔记·git·学习·gitee·ssh·github
漫步企鹅15 小时前
[Git] Git Stash 命令详解
git·git push·git pull·git commit·git pull rebase
船长@Quant17 小时前
协作开发攻略:Git全面使用指南 — 第二部分 高级技巧与最佳实践
git·版本控制·源代码管理·协作开发
用户126538387051219 小时前
github 和 gitee 配置问题及相关问题解决
git·github
极小狐20 小时前
极狐GitLab Git LFS 速率限制如何设置?
运维·git·ssh·gitlab·github
极小狐20 小时前
如何解决极狐GitLab 合并冲突?
人工智能·git·机器学习·gitlab
一袋米扛几楼9820 小时前
【GIT】github中的仓库如何删除?
git·github