在我們開發(fā)中,可能需要一個 Git 倉庫有多個遠(yuǎn)程做管理,或者同步。
比如本地的 git 庫,既想 push 到 gitlab ,又想推到 github 上,那么可以使用 remote 相關(guān)的命令處理。
全面的使用說明通過 help 查看
# brife
git remote -h
# detail
git remote --help
在入門系列第一篇中已經(jīng)提到,本地 git 項目如何推送到遠(yuǎn)程倉庫中
git remote add origin <url>
查看遠(yuǎn)程倉庫信息
通過以下命令查看當(dāng)前的遠(yuǎn)程庫
# 查看遠(yuǎn)程庫
$ git remote
origin
# 查看遠(yuǎn)程庫及地址
$ git remote -v
origin http://git.xxx (fetch)
origin http://git.xxx(push)
添加多個遠(yuǎn)程地址
添加 Git 項目添加多個遠(yuǎn)程地址,有兩種方式
添加一個遠(yuǎn)程地址 <url>,并命名<name>
1. 添加一個遠(yuǎn)程倉庫,獨立管理
命令為:
git remote add <name> <url>
示例:
- 指定一個默認(rèn)的遠(yuǎn)程庫 orgin
- 新增一個遠(yuǎn)程庫
git remote add tina https://github.com/tingtingtina/xxx.git - 有新的提交推到到 repo
git push(默認(rèn) 推到 origin) - 如果要同步到 遠(yuǎn)程庫 tina 中 需要手動指定倉庫別名 push
git push tina
$ git remote -v
origin http://git.xxx (fetch)
origin http://git.xxx (push)
tina https://github.com/tingtingtina/xxx.git (fetch)
tina https://github.com/tingtingtina/xxx.git (push)
從信息上也可以看出來,這兩個倉庫需要獨立管理。
2. 為指定倉庫設(shè)置多個遠(yuǎn)程地址
命令為:
git remote set-url --add <name> <url>
為名為 <name> 的倉庫關(guān)聯(lián)一個倉庫地址,不需要主動 push 多個倉庫,而是 push 指定倉庫,這個倉庫下配置的所有相關(guān)鏈接的倉庫都會更新。
示例
- 為 origin 添加一個鏈接
git remote set-url --add origin https://github.com/tingtingtina/xxx.git - 這時通過
git remote -v查看信息
origin 這個倉庫下就有配有多個地址了,當(dāng)git push的時候(默認(rèn)是 origin,也可指定<name>)這個名下所有的遠(yuǎn)程倉庫都會被更新。
$ git remote -v
origin http://git.xxx (fetch)
origin http://git.xxx (push)
origin https://github.com/tingtingtina/xxx.git (push)
擴(kuò)充
這兩種操作的本質(zhì)都是改變 git 的 config 配置文件
config 文件是當(dāng)前 git 項目根目錄下 .git/config (.git 目錄是隱藏文件)
使用 git config -e 命令行也可查看編輯內(nèi)容。
config 文件內(nèi)容
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = http://git.xxx
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
當(dāng) 使用 git remote add <name> <url> 時,追加 [remote "name"] 的標(biāo)簽
[remote "tina"]
url = https://github.com/tingtingtina/xxx.git
fetch = +refs/heads/*:refs/remotes/tina/*
使用 git remote set-url --add <name> <url> 會為名為<name> 的倉庫添加 url 連接,比如示例中, 在 origin 下會多出一個 url 的鍵值對
[remote "origin"]
url = http://git.xxx
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://github.com/tingtingtina/xxx.git
刪除關(guān)聯(lián)的遠(yuǎn)程庫
針對上面兩種設(shè)置方式,也有對應(yīng)的的刪除命令
# 刪除名為 <name> 的遠(yuǎn)程連接
git remote remove <name>
# 刪除 <name> 倉庫下的指定連接
git remote set-url --delete <name> <url>
重命名一個遠(yuǎn)程倉庫
git remote rename <old> <new>