新建分支:
git branch #查看本地所有分支
git checkout -b <branch name> #新建分支
删除分支:
1. 删除本地分支:
git branch #查看本地所有分支
git branch -d <branch name> #删除本地分支2. 删除远程分支:
git branch -a #查看本地和远程所有分支
git branch -r -d origin/<branch name> #删除远程分支
说明:
origin:在clone完成之后,Git会自动将此远程仓库命名为origin,并下载其中所有的数据,建立一个指向它的master分支的指针,用(远程仓库名)/(分支名) 这样的形式表示远程分支,所以origin/master指向的是一个remote branch(从那个remote branch clone数据到本地)。origin只相当于一个别名,运行git remote –v或者查看.git/config可以看到origin的含义。
HEAD:是指指针,指向当前分支的位置。
Fast forward:如果顺着一个分支走下去可以到达另一个分支的话,Git在合并两者时,只会简单地把指针右移,因为这种单线的历史分支不存在任何需要解决的分歧,所以这种合并过程可以称为快进(Fast forward)。
git remote -v #查看各个分支最后一个提交对象的信息
git log --oneline #查看git上目前的分支情况
git fetch 更新分支:
git fetch <remote name> #更新指定remote底下的分支,会读取remote repo的内容,并且更新remote branch的内容git fetch --all(等同于git remote update) #更新所有remote底下的分支
git pull 同步分支:
git checkout <branch name> #切换到<branch name>分支git pull <branch name> <remote name>
git push
git checkout <branch name>
git pull --rebase <branch name> <remote name>
git push
git merge 合并分支:
git checkout <branch name>git merge <merged branch name> #合并分支
git show --pretty=raw
git merge --no-ff <merged branch name> #强制产生merge patch
git show --pretty=raw
git branch --merged #查看哪些分支已被并入当前分支,也就是说哪些分支是当前分支的直接上游。
(列表中没有 * 的分支通常都可以用 git branch -d 来删掉)
git branch --no-merged #查看尚未合并的工作git merge --abort #抛弃合并过程并且尝试重建合并前的状态
遇到冲突时的分支合并:
首先试图使用git merge
会报错,然后用git status查看是哪个文件发生了冲突
然后用vim打开git status中提示出现冲突的文件,并手动解决冲突
git merge <branch name> git status vim xx.xx git status git add git commit -m "" git push origin <branch name>
总结:
尽量少用merge,除非两个branch的差异过大,主要原因是需要尽量确保分支的简单性,且每个patch容易拆解或重组。
Merge | Rebase |
---|---|
容易理解 | 不容易理解 |
会产生 Merge Patch,保存原始的 commit id | 重新 cherry-pick,重新产生 commit id |
当发生 conflict 的時候,全部在 Merge Patch 一次解完 | Rebase 的过程中,每次 cherry-pick 都可能会发生 conflict |
commit tree 会有两个 parents,不容易 trace code | commit 路徑單純,容易 trace code,或回到指定版本 |
git log 无法呈现合并前分支順序性 | git log 可以呈現正確的提交順序 |
过多的 Merge Patch 会看起来很乱 | 分支乾淨一致 |