git分支管理,git branch,git checkout

本文介绍了git分支管理常用命令,git创建分支git branch,git切换分支git checkout,git合并分支git merge

git分支管理介绍

所有的版本管理工具都会有分支的管理,使用分支意味着你可以从开发主线上分离开来,然后在不影响主线的同时继续工作。

Git 分支实际上是指向更改快照的指针。

创建分支命令:

git branch (branchname)

切换分支命令:

git checkout (branchname)

当你切换分支的时候,Git 会用该分支的最后提交的快照替换你的工作目录的内容, 所以多个分支不需要多个目录。

合并分支命令:

git merge

你可以多次合并到统一分支, 也可以选择在合并之后直接删除被并入的分支。

git分支管理

首先创建一个测试项目

$ mkdir gitdemo
$ cd gitdemo/
$ git init
Initialized empty Git repository...
$ touch README
$ git add README
$ git commit -m '第一次版本提交'
[master (root-commit) 3b58100] 第一次版本提交
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README

查看分支

列出分支基本命令:

git branch

没有参数时,git branch 会列出你在本地的分支。

$ git branch
* master

此例的意思就是,我们有一个叫做 master 的分支,并且该分支是当前分支。

当你执行 git init 的时候,默认情况下 Git 就会为你创建 master 分支。

如果我们要手动创建一个分支。执行 git branch (branchname) 即可。

$ git branch testing
$ git branch
* master
  testing

现在我们可以看到,有了一个新分支 testing。

当你以此方式在上次提交更新之后创建了新分支,如果后来又有更新提交, 然后又切换到了 testing 分支,Git 将还原你的工作目录到你创建分支时候的样子。

切换分支 git checkout

我们用 git checkout (branch) 切换到我们要修改的分支。

$ ls
README
$ echo 'catroom.com.cn' > test.txt
$ git add .
$ git commit -m 'add test.txt'
[master 3e92c19] add test.txt
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt
$ ls
README        test.txt
$ git checkout testing
Switched to branch 'testing'
$ ls
README

当我们切换到 testing 分支的时候,我们添加的新文件 test.txt 被移除了。切换回 master 分支的时候,它们又重新出现了。

$ git checkout master
Switched to branch 'master'
$ ls
README        test.txt

我们也可以使用 git checkout -b (branchname) 命令来创建新分支并立即切换到该分支下,从而在该分支中操作。

$ git checkout -b newtest
Switched to a new branch 'newtest'
$ git rm test.txt
rm 'test.txt'

$ ls
README

$ touch catroom.py

$ git add .

$ git commit -am 'removed test.txt、add catroom.py'
[newtest c1501a2] removed test.txt、add catroom.py
 2 files changed, 1 deletion(-)
 create mode 100644 catroom.py
 delete mode 100644 test.txt
$ ls
README        catroom.py

$ git checkout master
Switched to branch 'master'

$ ls
README        test.txt

如你所见,我们创建了一个分支,在该分支上移除了一些文件 test.txt,并添加了 catroom.py 文件,然后切换回我们的主分支,删除的 test.txt 文件又回来了,且新增加的 catroom.py 不存在主分支中。使用分支将工作切分开来,从而让我们能够在不同开发环境中做事,并来回切换。

删除分支

删除分支命令:

git branch -d (branchname)

例如我们要删除 testing 分支:

$ git branch
* master
  testing

$ git branch -d testing
Deleted branch testing (was 85fc7e7).

$ git branch
* master

合并分支 git merge

合并分支命令

git merge
$ git branch
* master
  newtest

$ ls
README        test.txt

$ git merge newtest
Updating 3e92c19..c1501a2
Fast-forward
 catroom.py | 0
 test.txt   | 1 -
 2 files changed, 1 deletion(-)
 create mode 100644 catroom.py
 delete mode 100644 test.txt

$ ls
README        catroom.py

以上实例中我们将 newtest 分支合并到主分支去,test.txt 文件被删除。

合并完后就可以删除分支:

$ git branch -d newtest
Deleted branch newtest (was c1501a2).

删除后, 就只剩下 master 分支了:

$ git branch
* master
上一篇 下一篇


推荐文章

评论
说点什么吧?

发表评论

取消回复
  最新文章