Git远程仓库管理

前言

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

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

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

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

查看远程仓库

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

bash 复制代码
$ git remote
origin

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

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

bash 复制代码
$ git remote -v
origin	ssh://git@gitlab.xxx.cn/git-demo.git (fetch)
origin	ssh://git@gitlab.xxx.cn/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>
相关推荐
GISer_Jing3 小时前
Git协作开发:feature分支、拉取最新并合并
大数据·git·elasticsearch
高山莫衣8 小时前
git rebase多次触发冲突
大数据·git·elasticsearch
码农藏经阁9 小时前
工作中常用的Git操作命令(一)
git
kobe_OKOK_9 小时前
【团队开发】git 操作流程
git·elasticsearch·团队开发
码农垦荒笔记9 小时前
Git 安装闭坑指南(仅 Windows 环境)
windows·git
CC码码19 小时前
管理你的多个 Git 密钥(多平台多账号)
git·gitlab·github
CC码码19 小时前
管理你的多个 Git 密钥(单平台多账号)
git·gitlab·github
大卫小东(Sheldon)19 小时前
GIM 1.5发布了! 支持Windows系统了
git·ai·rust
flying jiang19 小时前
将大仓库拆分为多个小仓库
git
李boyang10 天前
Git(四):远程操作
git