# 遠端指令與GitHub

若要和其他人分享專案，就必須將本地端儲存庫的特定版本，推(push)到遠端儲存庫整併，下一次要開發專案時，應先從遠端儲存庫將新版程式碼 fetch 回本地端儲存庫，再從本地端儲存庫 checkout 回工作目錄中，或是直接 pull 回工作目錄。

![](/files/-LC2Yy_s7TsSo1n0Imwx)

### 推送(push)資料至遠端儲存庫

遠端儲存庫也可以自行架設，例如使用 [GitLab Community Edition](https://gitlab.com/gitlab-org/gitlab-ce) ，但在此我們推薦直接使用 GitHub 進行免費的原始碼代管服務，以減少學習的複雜度，GitHub 延伸的線上服務還有可儲存程式碼片段的 [Gist](https://gist.github.com/)、 可撰寫手冊等電子書的 [GitBook](https://www.gitbook.com/) 等，都是很值得運用的好工具。

請先在 GitHub 建立名為 demo 的遠端儲存庫

![](/files/-LC2_7u2QJqg5dMudlvJ)

&#x20;預設使用 https 作為推送方式

![](/files/-LC2_KoNezkTMlBUykm5)

#### 設定遠端 repo 的 url <a href="#ding-duan-repo-de-url" id="ding-duan-repo-de-url"></a>

執行以下指令後，會將遠端儲存庫的名稱與 url 儲存在專案設定檔 .git/config

```
git remote add origin https://github.com/自己的帳號/demo.git
```

> 若要更改推送方式為 ssh ，則要執行 `git remote rm origin` 重設遠端儲存庫的 url，否則會發生錯誤 fatal: remote origin already exists

#### 查詢遠端 repo 設定 <a href="#cha-duan-repo-ding" id="cha-duan-repo-ding"></a>

執行以下指令後，可觀察目前遠端 repo 設定

```
git remote -v
```

#### 推送 local repo 至 remote repo <a href="#tui-song-local-repo-zhi-remote-repo" id="tui-song-local-repo-zhi-remote-repo"></a>

執行以下指令後，將本地端儲存庫 master 分支(預設分支)推送到遠端儲存庫 origin

```
git push -u origin master
```

> -u 參數是讓 git 將分支名稱記錄在專案設定檔 .git/config，下次就可以直接使用 git push 指令推出去了
>
> 從第一次 commit 開始，Git 就會建立預設分支，其名稱固定叫 master
>
> 實際的作用原理為將本地端的 master branch 與遠端的 master branch 作 fast-forward 合併。如果出現 \[rejected] 錯誤的話，表示你必須先作 pull

### 從遠端儲存庫將專案複製(clone)回來 <a href="#duan-cun-an-clone-hui" id="duan-cun-an-clone-hui"></a>

當不存在專案的本地端儲存庫時，執行 git clone 指令可把專案在遠端儲存庫上的所有內容複製到本地，建立起本機儲存庫與工作目錄，通常用於參考遠端儲存庫某專案的程式碼時使用。

```
mkdir testcd testgit clone https://github.com/自己的帳號/demo.git
```

### 從遠端儲存庫將專案拉(pull)回來 <a href="#duan-cun-an-la-pull-hui" id="duan-cun-an-la-pull-hui"></a>

已存在專案的本地端儲存庫時，執行以下指令後，會將專案的最新版本從遠端儲存庫拉回來並合併分支，通常用於協同開發時更新之用。

```
git pull origin master
```

> 實際是先 git fetch 遠端的 branch，然後與本地端的 branch 做 merge，產生一個 merge commit 節點

## 參考網頁 <a href="#kao" id="kao"></a>

* [ ] [Push 上傳到 GitHub](https://gitbook.tw/chapters/github/push-to-github.html)
* [ ] [Pull 下載更新](https://gitbook.tw/chapters/github/pull-from-github.html)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bwtit.gitbook.io/phpdev/ban-ben-guan-kong/duan-zhi-ling-github.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
