把本地仓库一次性推送到多个远程仓库。例如,同步推送到 Github 和 Gitee 上。
分两种情况:
- 使用 git clone 把远程仓库克隆到本地,push 到多个仓库。
- 使用 git init 初始化本发仓库,再添加内容,push 到多个仓库。
init 仓库
在 Github 和 Gitee 分别创建一个名称相同的仓库。
本地新建一个空目录,命令行进入空目录初始化为 Git 仓库。使用
git init
初始化为 Git 仓库。# 初始化为 git 仓库, 会创建一个 .git 的隐藏目录,里面是生成了 git 相关配置文件 git init
添加 2 个远程仓库地址,可以添加多个
注意
git remote add [<option>] <name> <url>
,name 指为origin
远程仓库,不是分支名。# 添加第一个远程仓库 git remote add origin https://github.com/gxing19/demo1.git # 添加第二个远程仓库 git remote set-url --add origin https://gitee.com/gxing19/demo1.git
查看已添加的远程仓库(origin)
# 查看已添加的远程仓库 git remote -v origin https://gitee.com/gxing19/demo1.git (fetch) origin https://gitee.com/gxing19/demo1.git (push) origin https://github.com/gxing19/demo1.git (push)
打开
.git/config
文件,可以看到内容如下:[remote "origin"] url = https://gitee.com/gxing19/demo1.git fetch = +refs/heads/*:refs/remotes/origin/* url = https://github.com/gxing19/demo1.git
添加远程仓库命令,实际也是操作 config 这个文件。如果不想使用命令,可直接编辑引文件,添加对应的远程仓库的 URL 即可。
当使用多个
git
平台时,可直接在远程仓库的 URL 中配置账号密码,格式如下:
https://username:password@github.com/username/xxxx.git# 多个 git 平台账号,直接编辑 config 文件,添加如下内容 [remote "origin"] url = https://username:password@github.com/username/demo1.git fetch = +refs/heads/*:refs/remotes/origin/* url = https://username:password@gitee.com/gxing19/demo1.git
在本地仓库添加文件,推送到 2 个远程仓库
git add * git commit -m 'first commit' git push origin --all # 强制推送到所有仓库 git push -f origin --all # 推送到指定分支,后续直接使用 git push 代替 git push origin master git push -u origin master # 集合前面两条命令的推送 git push -u -f origin --all
删除远程
origin
# 删除远程 origin git remote rm origin # 如果添加远程仓库映射时指定了映射名,删除时也指定映射名 git remote rm gitee
clone 仓库
如果本地仓库已存在,或本地仓库是从 git 平台上克隆(clone)下来的,现在要同时推送到多个 git 平台。
在新的 Git 平台上新建同步的仓库。
添加远程仓库地址,同上面【init仓库】章节的操作一样。
推送本地仓库到多个远程序仓。这里有一点与上面的不一样,首次需要强制推送。
# 第一次推送使用下面命令会报错 $ git push origin --all Everything up-to-date To https://gitee.com/gxing19/Spring-Boot-Example.git ! [rejected] master -> master (fetch first) error: failed to push some refs to 'https://gitee.com/gxing19/Spring-Boot-Example.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
是因为添加的远程仓库在本地不存在,需要强制推送:
# 强制推送到所有仓库 git push -f origin --all # 可带 -u 参数推送, 该参数为最新或成功推送的每个分支添加跟踪引用 git push -u -f orgin --all
相关参考
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载