# 初始化远程库

本节将介绍如何在本地创建一个git仓库，然后同步到远程的空仓库中。

1、在本地新建一个仓库

在某个目录下新建文件夹learngit，添加一个文件，初始化该git仓库

```
$ mkdir learngit
$ cd learngit
$ vi readme.md
$ git init
$ git add *
$ git commit -m "initialization"
```

2、初始化远程仓库

假设 `http://x.x.x.x:xx/pshizh/learngit.git` 是一个空仓库，执行以下命令把本地的learngit仓库同步到该仓库

```
$ cd learngit
$ git remote add origin http://x.x.x.x:xx/pshizh/learngit.git
$ git push -u origin master
```

`git remote add origin ...`

该语句表示为远程仓库 [http://x.x.x.x:xx/pshizh/learngit.git](http://x.x.x.x/:xx/pshizh/learngit.git) 设置一个别名origin

`git push -u origin master`

该语句表示把当前分支push到远程仓库origin（即[http://x.x.x.x:xx/pshizh/learngit.git） 的master分支](http://x.x.x.x/:xx/pshizh/learngit.git）的master分支)。参数 -u 的作用，是为当前分支设置upstream，即把当前分支与origin的master关联起来，当下次再在当前分支下执行push命令时，只需要执行\`git push\`就会把当前分支推送到origin的master分支。

## 附录：关联多个远程库

我们可以为本地的learngit仓库关联多个远程仓库。

假设 [http://y.y.y.y:yy/pshizh/learngit.git](http://y.y.y.y/:yy/pshizh/learngit.git) 也是一个空仓库，接着上面的第2步，我们继续初始化该远程仓库

首先为第二个远程仓库设置一个别名，比如为backup

```
$ cd learngit
$ git remote add backup http://y.y.y.y:yy/pshizh/learngit.git
```

然后，初始化远程仓库backup

```
$ git push backup master
```

此时，本地的learngit仓库就关联了两个远程仓库，一个名字叫origin，一个叫backup，我们可以通过以下的命令看到本地仓库关联的远程仓库

```
$ git remote -v
backup  http://y.y.y.y:yy/git/learngit.git (fetch)
backup  http://y.y.y.y:yy/git/learngit.git (push)
origin  http://x.x.x.x:xx/git/learngit.git (fetch)
origin  http://x.x.x.x:xx/git/learngit.git (push)
```

此时的本地仓库与两个远程仓库的关系图如下：

![](/files/-M69E375TjBJKRmAYGJf)

接着，我们修改master分支下的某个文件，然后push到origin远程仓库与backup远程仓库

```
$ cd learngit
$ vi readme.md
$ git add readme.md
$ git commit -m "first change"
$ git push
$ git push backup master
```

注意，倒数第二行 `git push` 等价于 `git push origin master` ，这里之所以可以省略， 这是因为前面在向 `origin master` push 的时候的命令为 `git push -u origin master`，加了 -u 参数，这意味着，本地的master分支关联着远程仓库 origin 的 master分支；而且后面向backup仓库push的时候的命令为 git push backup master ，并没有加 -u 参数，从而没有让本地master分支关联到backup的master分支。


---

# 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://pshizhsysu.gitbook.io/git/yuan-cheng-cang-ku/chu-shi-hua-yuan-cheng-ku.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.
