设置 Git 远程仓库
Stewart Nguyen
2022年4月22日
本文将介绍如何添加或删除远程仓库。
远程仓库是托管在某个地方的项目,例如 Github/Gitlab。
添加远程仓库允许我们使用短名称(别名)来执行命令,而不是输入整个远程 URL。
$ git fetch git@github.com:stwarts/git-demo.git
From github.com:stwarts/git-demo
* branch HEAD -> FETCH_HEAD
使用 git clone
时会自动设置一个名为 origin
的默认远程名称。
它的值是克隆的仓库。
$ git clone git@github.com:stwarts/git-demo.git
Cloning into 'git-demo'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.
$ cd git-demo
$ git remote -v
origin git@github.com:stwarts/git-demo.git (fetch)
origin git@github.com:stwarts/git-demo.git (push)
使用 git remote -v
列出所有远程的详细信息; 要仅显示名称,请使用 git remote
。
-v
选项代表--verbose
,它显示每个名称的相应 URL。
$ git remote
origin
$ git remote -v
origin git@github.com:stwarts/git-demo.git (fetch)
origin git@github.com:stwarts/git-demo.git (push)
在本地初始化仓库时,我们需要显式添加远程。
git remote add <name> <url>
$ git remote add alice_git_demo git@github.com:alice/git-demo.git
$ git remote -v
alice_git_demo git@github.com:alice/git-demo.git (fetch)
alice_git_demo git@github.com:alice/git-demo.git (push)
origin git@github.com:stwarts/git-demo.git (fetch)
origin git@github.com:stwarts/git-demo.git (push)
我们可以运行 git remote rename <old> <new>
来重命名现有的远程。
$ git remote rename alice_git_demo stwarts_git_demo
origin git@github.com:stwarts/git-demo.git (fetch)
origin git@github.com:stwarts/git-demo.git (push)
stwarts_git_demo git@github.com:alice/git-demo.git (fetch)
stwarts_git_demo git@github.com:alice/git-demo.git (push)
使用 git remote remove <name>
删除跟踪的仓库。
$ git remote remove stwarts_git_demo
$ git remote remove origin
$ git remote add stwarts_git_demo git@github.com:stwarts/git-demo.git
$ git remote -v
stwarts_git_demo git@github.com:stwarts/git-demo.git (fetch)
stwarts_git_demo git@github.com:stwarts/git-demo.git (push)
stwarts_git_demo
名称已准备好用于共享数据。
$ git fetch stwarts_git_demo
From github.com:stwarts/git-demo
* [new branch] main -> stwarts_git_demo/main
$ touch file.txt
$ git add file.txt && git commit -m 'Add file.txt'
[main 80bf058] Add file.txt
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 file.txt
$ git push stwarts_git_demo main
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 12 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 281 bytes | 93.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To github.com:stwarts/git-demo.git
dd38fe8..80bf058 main -> main