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>
相关推荐
2501_9032386513 分钟前
Git Bash:Windows下的强大命令行工具
windows·git·bash·个人开发
神明木佑2 小时前
datalist 是什么?以及作用是什么?
git
那片海还在吗4 小时前
使用 Git、Postman、Newman、Jenkins 与邮件构建自动化接口测试及通知流程
git·jenkins·postman
heeheeai12 小时前
git 国内源
git
the_seventh_dog12 小时前
git | 团队协作开发注意事项
git
yinshuilan15 小时前
今日运维之-Mac笔记本python环境问题
运维·git·python·brew
辄也16 小时前
git拉取远程分支到本地分支
git
皮克斯的进化之路16 小时前
Git原理+使用(超详细)
git
wrjwww16 小时前
【Git学习笔记】Git常用命令
笔记·git·学习
大乔乔布斯17 小时前
WSL,Power shell 和CMD, Git bash的区别
开发语言·git·bash