# 创建分支并与推送到远程

## 创建分支应在代码改动前还是改动后

创建brach的动作, 是从当前branch的**HEAD commit**处开辟一个分路. 开辟新branch时, 相对于HEAD commit的情况, 本地文件可能有两种状态:

* 没有任何改动
* 代码有改动, 部分处于`modified`状态(修改但未ADD), 部分处于`staged`状态(ADD但未COMMIT)

如果代码没有改动, 创建分支后的开发流程就是标准的流程. 如果代码有改动, 无论改动处于哪种状态(`modified`或`staged`), 在创建分支之后, 这些改动都将跟随到新的分支上来. 使用`git status`在创建并切换分支前后, 看到的内容是完全相同的.

这是因为branch其实就是将一个个`commit`节点串联起来, 创建分支是在一个`commit`节点处引出一条分路, 分路的下一个节点一定也是一个`commit`. 而没有`commit`的改动是不会因分支而区别的.

## 本地创建分支

可以使用以下两种方式创建一个新的分支.

```bash
git branch [branch-name]
```

上面的指令会创建一个名为`branch-name`的分支, 但仍然停留在当前的分支, 而本地已经有这个分支了, 如果需要使用新分支, 需要手动切换过去.

```bash
git checkout -b [branch-name]
```

这个指令在创建新分支的同时, 就会切换到新的工作分支上. 如果创建分支前就有未提交的改动代码, 需要在新分支上使用, 使用这个指令会更方便.

## 同步新分支到远程

通过上面一步, 只是在本地创建了新的分支, 远程仓库中还没有这个新的分支. 将本地的新分支推送到远程, 在远程也同步创建一个新的分支, 需要首先切换到新分支下面, 使用如下的指令:

```bash
git push --set-upstream origin [origin-branch-name]
git push -u origin [origin-branch-name]
```

其中:

* `--set-upstream`与`-u`是等价的. 此参数的意思是**指定当前的本地分支与远程分支的跟踪关系**, 相当于在本地和远程远程之间建立绑定关系
* `origin`代表远程
* `[origin-branch-name]`远程分支的名称. 允许本地分支与远程分支不同, 但一般都会保持名称的一致, 避免混乱


---

# 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://kerasnoone.gitbook.io/garnet/gong-cheng-zhan/git/fen-zhi/chuang-jian-fen-zhi-bing-yu-tui-song-dao-yuan-cheng.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.
