首页 > 代码库 > Git分支管理及常见操作

Git分支管理及常见操作

  众所周知,使用Git分支,我们可以从开发主线上分离开来,然后在不影响主线的同时继续工作。

  既然要使用Git分支,这里就涉及到Git分支的管理及常见操作,如列出分支,分支的创建,分支的删除,分支的合并等操作。

  以前看到这就头痛,总是搞不明白,今天研究了许久才搞懂,这里做个笔记。

  如,我的Git工具安装在E盘>myGit中,安装后目录如下:

  技术分享

  我本地创建的仓库为myProject,首先我们可以先查看下本地仓库的分支情况。打开Git工具,操作如下。 

jiangfeng@jiangfeng MINGW64 ~/桌面$ cd e:jiangfeng@jiangfeng MINGW64 /e$ cd mygitjiangfeng@jiangfeng MINGW64 /e/mygit$ cd gitjiangfeng@jiangfeng MINGW64 /e/mygit/git$ cd myProject

  检查本地仓库分支,命令,git branch回车即可查看该仓库下的分支情况,如果没有创建的话,默认只有主分支master:

jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (master)$ git branch  查看该仓库下的分支情况* master

  

  下面,创建分支,如,我在该仓库下创建了分支test,然后在该分支下写了一个test.txt文件。那么这里就涉及到两个操作了,即分支的创建与切换。具体操作如下: 

jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (master)$ git branch test   test为创建的分支名jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (master)$ git checkout test   从主分支master上切换到刚创建的分支test上Switched to branch testjiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (test)$ echo "hello world!" >test.txt  在分支test里写入一个test.txt文件,文件内容为“hello world!”

  

  下面要将刚创建的文件写入到缓存区。操作如下:  

jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (test)$ git add .   将文件写入到缓存区中,注意add与逗号间有空格warning: LF will be replaced by CRLF in test.txt.The file will have its original line endings in your working directory.

  

  然后要将缓存区内容test.txt文件添加到仓库,操作如下: 

jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (test)$ git commit -m "change log"  将缓存区内容添加到仓库[test afc4b17] change log 1 file changed, 1 insertion(+) create mode 100644 test.txt

 

  下面要进行分支合并,即将新建的分支test合并到主分支master上,这里首先要向将分支test切换到主分支master,然后进行分支合并。操作如下:

jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (test)$ git checkout master  切换分支test到主分支master上Switched to branch masterYour branch is up-to-date with origin/master.jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (master)$ git merge test  将分支test合并到主分支master上Updating 68d8bfc..afc4b17Fast-forward test.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 test.txt

  

  如果,我们要将本地仓库里的内容提交到远程GitHub上,操作如下: 

jiangfeng@jiangfeng MINGW64 /e/mygit/git/myProject (master)$ git push origin master  提交内容到远程GitHub上Counting objects: 3, done.Delta compression using up to 4 threads.Compressing objects: 100% (2/2), done.Writing objects: 100% (3/3), 282 bytes | 0 bytes/s, done.Total 3 (delta 1), reused 0 (delta 0)remote: Resolving deltas: 100% (1/1), completed with 1 local object.To https://github.com/leiwuhen-67/project.git   68d8bfc..afc4b17  master -> master

 

  总结:

  1、查看分支:git branch

  2、创建分支:git branch  分支名

  3、删除分支:git branch -d 分支名

  4、切换分支:git checkout 新建分支名

  5、合并分支:git merge 新建分支名

Git分支管理及常见操作