1. 程式人生 > >Git同時提交到多個遠端倉庫

Git同時提交到多個遠端倉庫

在已經習慣使用git同步寫程式碼,github無疑是最的託管平臺,但是國內由於“你懂的”原因,速度很慢,有時無法訪問,於是想把自己的程式碼同步到多個不同的遠端倉庫備份。

我的主要倉庫:

另外,國內還有coding(原來的gitcafe合併到了coding),csdn code等。

新增同名多遠端倉庫

新增一個remote,這裡是all,也可以是別的名字(如origin)

git remote add all https://github.com/wonux.test.git

再新增另一個:

git remote set-url --add all https://git.oschina.net/wonux/test.git

重複向同一個遠端倉庫名字新增需要set-url --add引數

如果有多個,按照上面這一個命令進行新增.

向多遠端倉庫推送程式碼

git push all --all

這樣就會一次提交到多個庫了,上面命令輸出如下:

git push all --all
Username for 'https://github.com': wonux
Password for 'https://[email protected]': 
Counting objects: 68, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (56/56), done.
Writing objects: 100% (68/68), 72.16 KiB | 0 bytes/s, done.
Total 68 (delta 13), reused 0 (delta 0)
To https://github.com/wonux/test.git
 * [new branch]      master -> master
Username for 'https://git.oschina.net': wonux
Password for 'https://[email protected]': 
Counting objects: 68, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (56/56), done.
Writing objects: 100% (68/68), 72.16 KiB | 0 bytes/s, done.
Total 68 (delta 13), reused 0 (delta 0)
To https://git.oschina.net/wonux/test.git
 * [new branch]      master -> master

記住不要忘記--all引數,如果不加--all,則無法推送,提示:

git push all
warning: push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:
  git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
  git config --global push.default simple
When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.
Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.
See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)
fatal: unable to access 'https://github.com/wonux/test.git/': Couldn't resolve host 'github.com'

分析配置檔案

在操作完上面的新增命令後,如果我們開啟.git/config檔案,我們可以看到這樣的配置:

[remote "all"]
	url = https://github.com/wonux/test.git
	fetch = +refs/heads/*:refs/remotes/all/*
	url = https://git.oschina.net/wonux/test.git

因此,直接在.git/config檔案中新增:

[remote "all"]
	url = https://github.com/wonux/test.git
	fetch = +refs/heads/*:refs/remotes/all/*
	url = ……

有多少個遠端庫,就配置多少個url即可.
從這裡可以看出,第一種方法生成的配置中還有一個fetch配置,這個配置可以完全去掉.