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>
相关推荐
小猪咪piggy1 小时前
【工具】Git 和小乌龟安装与使用
git
二进制coder2 小时前
Git 实操:已Push的Commit能否重新Push?答案与规范全解析
git
solly7937556705 小时前
IDEA下载git项目和配置tomcat
git·tomcat·intellij-idea
拐爷6 小时前
Vibe‑coding九阳神功之夯:Git 基础操作,AI 时代的刹车系统(附速查表)
人工智能·git
嘿吖嘿嘿~7 小时前
怎么解决git@github.com出现Permission denied (publickey)的问题
git·github
岱宗夫up17 小时前
Git不是工具,是协作哲学
git
生活很暖很治愈17 小时前
Linux基础开发工具
linux·服务器·git·vim
极地星光19 小时前
如何使用 Git 实现 revert
git
厨 神19 小时前
IFLOW-Git-Claude
git·cloudera
ghostwritten1 天前
git 发布版本
git