分支即是平行空间,假设你在为某个手机系统研发拍照功能,代码已经完成了80%,但如果将这不完整的代码直接提交到git仓库中,又有可能影响到其他人的工作,此时我们便可以在该软件的项目之上创建一个名叫“拍照功能”的分支,这种分支只会属于你自己,而其他人看不到,等代码编写完成后再与原来的项目主分支合并下即可,这样即能保证代码不丢失,又不影响其他人的工作。

说明: Git团队合作流程图

一般在实际的项目开发中,我们要尽量保证master分支是非常稳定的,仅用于发布新版本,平时不要随便直接修改里面的数据文件,而工作的时候则可以新建不同的工作分支,等到工作完成后在合并到master分支上面,所以团队的合作分支看起来会像上面图那样。

说明: Git分支示意图

1、创建本地分支

[root@linux-node5 test]# git branch about
[root@linux-node5 test]# git branch  #查看本地分支
  about
* master

2、切换分支

[root@linux-node5 test]# git checkout about 
Switched to branch 'about'
[root@linux-node5 test]# git status 
On branch about

3、查看分支about文件

[root@linux-node5 test]# ll
total 12
-rw-r--r-- 1 root root  4 Mar 28 16:25 index.html
-rw-r--r-- 1 root root  5 Mar 28 16:29 news.html
-rw-r--r-- 1 root root 11 Mar 28 16:32 pay.html

4、在about分支上开发并提交代码

[root@linux-node5 test]# touch about.html
[root@linux-node5 test]# git add .
[root@linux-node5 test]# git commit -m "about"
[about 7ecca1f] about
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 about.html

[root@linux-node5 test]# echo "ooo" >> about2.html 
[root@linux-node5 test]# git add .
[root@linux-node5 test]# git commit -m "about2"
[about 912f315] about2
 1 file changed, 1 insertion(+)
 create mode 100644 about2.html

5、切换到master分支

[root@linux-node5 test]# git checkout master 
Switched to branch 'master'

6、把about分支合并到master(合并分支)

[root@linux-node5 test]# git merge about
Updating 6ab971b..912f315
Fast-forward
 about.html  | 0
 about2.html | 1 +
 2 files changed, 1 insertion(+)
 create mode 100644 about.html
 create mode 100644 about2.html

7、查看已合并的分支及未合并的分支

[root@linux-node5 test]# git branch test
[root@linux-node5 test]# git checkout test 
Switched to branch 'test'
[root@linux-node5 test]# echo "test" >>test.html
[root@linux-node5 test]# git add .
[root@linux-node5 test]# git commit -m "test"
[test 5748933] test
 1 file changed, 1 insertion(+)
 create mode 100644 test.html

已合并的分支

[root@linux-node5 test]# git branch --merged 
  about
* master

没有合并的分支

[root@linux-node5 test]# git branch --no-merged 
  test
[root@linux-node5 test]# 
[root@linux-node5 test]# git branch
  about
* master
  test

8、删除分支

[root@linux-node5 test]# git branch -d about 
Deleted branch about (was 912f315).
[root@linux-node5 test]# git branch 
* master
  test

9、命令

命令 git branch //列出所有本地分支
命令git branch –r  //列出所有远程分支
命令git branch –a  //列出所有本地分支和远程分支
命令git branch [branch-name]  //创建新分支
命令git checkout –b [branch-name] //创建新分支,并且切换到该分支
命令 git branch  --track [branch] [remote-branch]   //创建新分支,与指定的远程分支建立追踪关系
命令 git checkout [branch-name]      //切换至指定分支
命令 git branch –set-upstream [branch] [remote-branch] //本地分支与远程分支建立追踪关系
命令 git merge [branch] //合并指定分支到当前分支
命令 git cherry-pick [commit] //选择一个commit,合并至当前分支
命令git branch –d [branch-name]  //删除本地分支
命令git push origin --delete [branch-name]  //删除远程分支
命令git branch –dr [remote/branch]   //删除远程分支
文档更新时间: 2019-03-28 17:48   作者:李延召