設定 Git 遠端倉庫

Stewart Nguyen 2022年4月22日
設定 Git 遠端倉庫

本文將介紹如何新增或刪除遠端倉庫。

遠端倉庫是託管在某個地方的專案,例如 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

相關文章 - Git Remote