Git同时推送多个远程仓库
准备工作
需要准备哪些环境。自然是一个本地的git仓库。
mkdir git-test
cd git-test
git init
touch README.md
具体操作
首先思考的是如何在一个项目中添加两个远程仓库下面的命令可以给仓库添加远程仓库。
git remote add [shortname] [url]
PS:我们解释一下这行命令的两个参数,第一个参数其实就是我们后面推送到这个远程仓库的时候都使用这个名称来代替仓库地址,第二个参数就是远程仓库的地址了,这句命令应该很好理解。
然后就在本地仓库根目录执行了下面两行命令,为本地仓库添加了两个远程仓库。
git remote add gitee https://gitee.com/gancy/git-test.git
git remote add github https://github.com/ganchaoyang/git-test.git
另外,为了后续操作,再添加一条命令,将origin指向上述一个远程仓库。
origin是git的默认[shortname],git push
等同于git push [shortname]
git remote add origin https://gitee.com/gancy/git-test.git
然后我们修改README文件后,可以分别往两个仓库推送代码。
git add *
git commit -m "first commit"
git push -u github master
git push -u gitee master
通过两句git push
命令我们确实可以向两个远程仓库推送代码,但是有没有一种方式可以一句命令就同时push到两个远程仓库。于是乎就有了下面的操作。直接修改了.git/config文件中的内容。原文件内容如下:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "gitee"]
url = https://gitee.com/gancy/git-test.git
fetch = +refs/heads/*:refs/remotes/gitee/*
[remote "github"]
url = https://github.com/ganchaoyang/git-test.git
fetch = +refs/heads/*:refs/remotes/github/*
[branch "master"]
remote = gitee
merge = refs/heads/master
修改后的内容为:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "gitee"]
url = https://gitee.com/gancy/git-test.git
fetch = +refs/heads/*:refs/remotes/gitee/*
[remote "github"]
url = https://github.com/ganchaoyang/git-test.git
fetch = +refs/heads/*:refs/remotes/github/*
[remote "origin"]
url = https://gitee.com/gancy/git-test.git
url = https://github.com/ganchaoyang/git-test.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
只是将两个remote
合并成了一个而已,然后再执行git push
命令就会发现,会一次性向两个仓库push
代码了。
使用git remote -v
查看状态,会看见pull
从一个远程仓库拉取,push
同时推送两个远程仓库。
结束语
这篇文章,主要是讲了如何同时向多个远程仓库推送代码。虽然平时使用场景不多,但是偶尔遇到了这样的需求还是很实用的。