Git 分支操作介绍
Git

> 
> 在这个 Git 入门系列的第三篇中，我们来学习一下如何添加和删除 Git 分支。
> 
> 
> 


![](/data/attachment/album/201806/07/232158l3slzxx33kezcc5x.jpg)


在本系列的前两篇文章中，我们[开始使用 Git](/article-9319-1.html)，学会如何[克隆项目，修改、增加和删除内容](/article-9517-1.html)。在这第三篇文章中，我将介绍 Git 分支，为何以及如何使用分支。


![树枝](/data/attachment/album/201806/07/232258bokj2oqrqh5ior0i.jpg "tree branches")


不妨用树来描绘 Git 仓库。图中的树有很多分支，或长或短，或从树干延伸或从其它分支延伸。在这里，我们用树干比作仓库的 master 分支，其中 `master` 代指 ”master 分支”，是 Git 仓库的中心分支或第一个分支。为简单起见，我们假设 `master` 是树干，其它分支都是从该分支分出的。


### 为何在 Git 仓库中使用分支


使用分支的主要理由为：


* 如果你希望为项目增加新特性，但很可能会影响当前可正常工作的代码。对于该项目的活跃用户而言，这是很糟糕的事情。与其将特性加入到其它人正在使用的 `master` 分支，更好的方法是在仓库的其它分支中变更代码，下面会给出具体的工作方式。
* 更重要的是，[Git 其设计](https://en.wikipedia.org/wiki/Git)用于协作。如果所有人都在你代码仓库的 `master` 分支上操作，会引发很多混乱。对编程语言或项目的知识和阅历因人而异；有些人可能会编写有错误或缺陷的代码，也可能会编写你觉得不适合该项目的代码。使用分支可以让你核验他人的贡献并选择适合的加入到项目中。（这里假设你是代码库唯一的所有者，希望对增加到项目中的代码有完全的控制。在真实的项目中，代码库有多个具有合并代码权限的所有者）


### 创建分支


让我们回顾[本系列上一篇文章](/article-9517-1.html)，看一下在我们的 Demo 目录中分支是怎样的。如果你没有完成上述操作，请按照文章中的指示从 GitHub 克隆代码并进入 Demo 目录。运行如下命令：



```
pwd
git branch
ls -la

```

`pwd` 命令（是当前工作目录的英文缩写）返回当前你所处的目录（以便确认你在 `Demo` 目录中），`git branch` 列出该项目在你主机上的全部分支，`ls -la` 列出当前目录下的所有文件。你的终端输出类似于：


![终端输出](/data/attachment/album/201806/07/232259fulowhuxc3vmyuyv.png "Terminal output")


在 `master` 分支中，只有一个文件 `README.md`。（Git 会友好地忽略掉其它目录和文件。）


接下来，运行如下命令：



```
git status
git checkout -b myBranch
git status

```

第一条命令 `git status` 告知你当前位于 `branch master`，（就像在终端中看到的那样）它与 `origin/master` 处于同步状态，这意味着 master 分支的本地副本中的全部文件也出现在 GitHub 中。两份副本没有差异，所有的提交也是一致的。


下一条命令 `git checkout -b myBranch` 中的 `-b` 告知 Git 创建一个名为 `myBranch` 的新分支，然后 `checkout` 命令将我们切换到新创建的分支。运行第三条命令 `git status` 确保你已经位于刚创建的分支下。


如你所见，`git status` 告知你当前处于 `myBranch` 分支，没有变更需要提交。这是因为我们既没有增加新文件，也没有修改已有文件。


![终端输出](/data/attachment/album/201806/07/232307zypoojs93o2zjgt9.png "Terminal output")


如果希望以可视化的方式查看分支，可以运行 `gitk` 命令。如果遇到报错 `bash: gitk: command not found...`，请先安装 `gitk` 软件包（找到你操作系统对应的安装文档，以获得安装方式）。


（LCTT 译注：需要在有 X 服务器的终端运行 `gitk`，否则会报错）


下图展示了我们在 Demo 项目中的所作所为：你最后一次提交（的对应信息）是 `Delete file.txt`，在此之前有三次提交。当前的提交用黄点标注，之前的提交用蓝点标注，黄点和 `Delete file.txt` 之间的三个方块展示每个分支所在的位置（或者说每个分支中的最后一次提交的位置）。由于 `myBranch` 刚创建，提交状态与 `master` 分支及其对应的记为 `remotes/origin/master` 的远程 `master` 分支保持一致。（非常感谢来自 Red Hat 的 [Peter Savage](https://opensource.com/users/psav) 让我知道 `gitk` 这个工具）


![Gitk 输出](/data/attachment/album/201806/07/232308luoexoj2j3lo22l3.png "Gitk output")


下面让我们在 `myBranch` 分支下创建一个新文件并观察终端输出。运行如下命令：



```
echo "Creating a newFile on myBranch" > newFile
cat newFile
git status

```

第一条命令中的 `echo` 创建了名为 `newFile` 的文件，接着 `cat newFile` 打印出文件内容，最后 `git status` 告知你我们 `myBranch` 分支的当前状态。在下面的终端输出中，Git 告知 `myBranch` 分支下有一个名为 `newFile` 的文件当前处于 `untracked` 状态。这表明我们没有让 Git 追踪发生在文件 `newFile` 上的变更。


![终端输出](/data/attachment/album/201806/07/232318mp3a74p35nnl9ztt.png "Terminal output")


下一步是增加文件，提交变更并将 `newFile` 文件推送至 `myBranch` 分支（请回顾本系列上一篇文章获得更多细节）。



```
git add newFile
git commit -m "Adding newFile to myBranch"
git push origin myBranch

```

在上述命令中，`push` 命令使用的分支参数为 `myBranch` 而不是 `master`。Git 添加 `newFile` 并将变更推送到你 GitHub 账号下的 Demo 仓库中，告知你在 GitHub 上创建了一个与你本地副本分支 `myBranch` 一样的新分支。终端输出截图给出了运行命令的细节及命令输出。


![终端输出](/data/attachment/album/201806/07/232321zg9070fg08c9cnft.png "Terminal output")


当你访问 GitHub 时，在分支选择的下拉列表中可以发现两个可供选择的分支。


![GitHub](/data/attachment/album/201806/07/232339fb7lfez7jnkzbele.png "GitHub")


点击 `myBranch` 切换到 `myBranch` 分支，你可以看到在此分支上新增的文件。


![GitHub](/data/attachment/album/201806/07/232350w3c7phg2cswcbvs7.png "GitHub")


截至目前，我们有两个分支：一个是 `master` 分支，只有一个 `README.md` 文件；另一个是 `myBranch` 分支，有两个文件。


你已经知道如何创建分支了，下面我们再创建一个分支。输入如下命令：



```
git checkout master
git checkout -b myBranch2
touch newFile2
git add newFile2
git commit -m "Adding newFile2 to myBranch2"
git push origin myBranch2

```

我不再给出终端输出，需要你自己尝试，但你可以在 [GitHub 代码库](https://github.com/kedark3/Demo/tree/myBranch2) 中验证你的结果。


### 删除分支


由于我们增加了两个分支，下面删除其中的一个（`myBranch`），包括两步：


1. **删除本地分支** 你不能删除正在操作的分支，故切换到 `master` 分支 （或其它你希望保留的分支），命令及终端输出如下：


![](/data/attachment/album/201806/07/232356sfpovd4o9cjjnsps.png)


`git branch` 可以列出可用的分支，使用 `checkout` 切换到 `master` 分支，然后使用 `git branch -D myBranch` 删除该分支。再次运行 `git branch` 检查是否只剩下两个分支（而不是三个）。
2. **删除 GitHub 上的分支** 使用如下命令删除 `myBranch` 的远程分支：



```
git push origin :myBranch

```

![Terminal output](/data/attachment/album/201806/07/232357g7s9vioukdh729k2.png "Terminal output")


上面 `push` 命令中分支名称前面的冒号（`:`）告知 GitHub 删除分支。另一种写法为：



```
git push -d origin myBranch

```

其中 `-d` (也可以用 `--delete`) 也用于告知 GitHub 删除你的分支。


我们学习了 Git 分支的使用，在本系列的下一篇文章中，我们将介绍如何执行 `fetch` 和 `rebase` 操作，对于多人同时的贡献的项目而言，这是很必须学会的。




---


via: <https://opensource.com/article/18/5/git-branching>


作者：[Kedar Vijay Kulkarni](https://opensource.com/users/kkulkarn) 选题：[lujun9972](https://github.com/lujun9972) 译者：[pinewall](https://github.com/pinewall) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
In my two previous articles in this series, we [started using Git](https://opensource.com/article/18/1/step-step-guide-git) and learned how to [clone, modify, add, and delete](https://opensource.com/article/18/2/how-clone-modify-add-delete-git-files) Git files. In this third installment, we'll explore Git branching and why and how it is used.

Picture this tree as a Git repository. It has a lot of branches, long and short, stemming from the trunk and stemming from other branches. Let's say the tree's trunk represents a master branch of our repo. I will use `master`

in this article as an alias for "master branch"—i.e., the central or first branch of a repo. To simplify things, let's assume that the `master`

is a tree trunk and the other branches start from it.

## Why we need branches in a Git repo


The main reasons for having branches are:

- If you are creating a new feature for your project, there's a reasonable chance that adding it could break your working code. This would be very bad for active users of your project. It's better to start with a prototype, which you would want to design roughly in a different branch and see how it works, before you decide whether to add the feature to the repo's
`master`

for others to use. - Another, probably more important, reason is
[Git was made](https://en.wikipedia.org/wiki/Git)for collaboration. If everyone starts programming on top of your repo's`master`

branch, it will cause a lot of confusion. Everyone has different knowledge and experience (in the programming language and/or the project); some people may write faulty/buggy code or simply the kind of code/feature you may not want in your project. Using branches allows you to verify contributions and select which to add to the project. (This assumes you are the only owner of the repo and want full control of what code is added to it. In real-life projects, there are multiple owners with the rights to merge code in a repo.)

## Adding a branch

Let's go back to the [previous article in this series](https://opensource.com/article/18/2/how-clone-modify-add-delete-git-files) and see what branching in our *Demo* directory looks like. If you haven't yet done so, follow the instructions in that article to clone the repo from GitHub and navigate to *Demo*. Run the following commands:

```
pwd
git branch
ls -la
```


The `pwd`

command (which stands for present working directory) reports which directory you're in (so you can check that you're in *Demo*), `git branch`

lists all the branches on your computer in the *Demo* repository, and `ls -la`

lists all the files in the PWD. Now your terminal will look like this:

There's only one file, `README.md`

, on the branch master. (Kindly ignore the other directories and files listed.)

Next, run the following commands:

```
git status
git checkout -b myBranch
git status
```


The first command, `git status`

reports you are currently on `branch master`

, and (as you can see in the terminal screenshot below) it is up to date with `origin/master`

, which means all the files you have on your local copy of the branch master are also present on GitHub. There is no difference between the two copies. All commits are identical on both the copies as well.

The next command, `git checkout -b myBranch`

, `-b`

tells Git to create a new branch and name it `myBranch`

, and `checkout`

switches us to the newly created branch. Enter the third line, `git status`

, to verify you are on the new branch you just created.

As you can see below, `git status`

reports you are on branch `myBranch`

and there is nothing to commit. This is because there is neither a new file nor any modification in existing files.

If you want to see a visual representation of branches, run the command `gitk`

. If the computer complains `bash: gitk: command not found…`

, then install `gitk`

. (See documentation for your operating system for the install instructions.)

The image below reports what we've done in *Demo*: Your last commit was `Delete file.txt`

and there were three commits before that. The current commit is noted with a yellow dot, previous commits with blue dots, and the three boxes between the yellow dot and `Delete file.txt`

tell you where each branch is (i.e., what is the last commit on each branch). Since you just created `myBranch`

, it is on the same commit as `master`

and the remote counterpart of `master`

, namely `remotes/origin/master`

. (A big thanks to [Peter Savage](https://opensource.com/users/psav) from Red Hat who made me aware of `gitk`

.)

Now let's create a new file on our branch `myBranch`

and let's observe terminal output. ** **Run the following commands:

```
echo "Creating a newFile on myBranch" > newFile
cat newFile
git status
```


The first command, `echo`

, creates a file named `newFile`

, and `cat newFile`

shows what is written in it. `git status`

tells you the current status of our branch `myBranch`

. In the terminal screenshot below, Git reports there is a file called `newFile`

on `myBranch`

and `newFile`

is currently `untracked`

. That means Git has not been told to track any changes that happen to `newFile`

.

The next step is to add, commit, and push `newFile`

to `myBranch`

(go back to the last article in this series for more details).

```
git add newFile
git commit -m "Adding newFile to myBranch"
git push origin myBranch
```


In these commands, the branch in the `push`

command is `myBranch`

instead of `master`

. Git is taking `newFile`

, pushing it to your *Demo* repository in GitHub, and telling you it's created a new branch on GitHub that is identical to your local copy of `myBranch`

. The terminal screenshot below details the run of commands and its output.

If you go to GitHub, you can see there are two branches to pick from in the branch drop-down.

Switch to `myBranch`

by clicking on it, and you can see the file you added on that branch.

Now there are two different branches; one, `master`

, has a single file, `README.md`

, and the other, `myBranch`

, has two files.

Now that you know how to create a branch, let's create another branch. Enter the following commands:

```
git checkout master
git checkout -b myBranch2
touch newFile2
git add newFile2
git commit -m "Adding newFile2 to myBranch2"
git push origin myBranch2
```


I won't show this terminal output as I want you to try it yourself, but you are more than welcome to check out the [repository on GitHub](https://github.com/kedark3/Demo/tree/myBranch2).

## Deleting a branch

Since we've added two branches, let's delete one of them (`myBranch`

) using a two-step process.

**1. Delete the local copy of your branch:** Since you can't delete a branch you're on, switch to the `master`

branch (or another one you plan to keep) by running the commands shown in the terminal image below:

![terminal Step 1.Delete the local copy of your branch](https://opensource.com/sites/default/files/pictures/kulkarni_fig_new.png)

`git branch`

lists the available branches; `checkout`

changes to the `master`

branch and `git branch -D myBranch`

removes that branch. Run `git branch`

again to verify there are now only two branches (instead of three).

**2. Delete the branch from GitHub:** Delete the remote copy of `myBranch`

by running the following command:

`git push origin :myBranch`


The colon (`:`

) before the branch name in the `push`

command tells GitHub to delete the branch. Another option is:

`git push -d origin myBranch`


as `-d`

(or `--delete`

) also tells GitHub to remove your branch.

Now that we've learned about using Git branches, in the next article in this series we'll look at how to fetch and rebase branch operations. These are essential things to know when you are working on a project with multiple contributors.

## 2 Comments