继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

分支管理

为爱心太软
关注TA
已关注
手记 170
粉丝 1.4万
获赞 860

创建分支

git branch <分支名>
git push -u origin <分支名> # 将新建分支同步到远程仓库
git push --set-upstream origin <分支名> # 将新建分支同步到远程仓库

例子:

创建分支 hotfix 之前,只有主分支 main:
图片描述

切换到 main 分支,然后创建 hotfix 分支:

$ git checkout main
$ git branch hotfix

图片描述

切换分支

git checkout <分支名>

例子:

$ git checkout hotfix
Switched to branch 'hotfix'

图片描述
如果想新建一个分支并切换到那个分支上,可以执行添加 -b 的 git checkout

git checkout -b <分支名>

储藏修改

在切换分支的时候,如果工作区和暂存区里还有没被提交的内容,由于分支之间的冲突,GIT 会阻止你切换到别的分支。
最好的办法是通过 git stash 或者 git stash save 指令储藏当前分支的修改,如此一来,就可以切换到别的分支进行工作了。

$ git stash
Saved working directory and index state WIP on main: c9d6d53 Update hello.js

如果想查看储存的东西,可以执行 git stash list 指令:

$ git stash list
stash@{0}: WIP on test1: f163bf8 test1
stash@{1}: WIP on main: c9d6d53 Update hello.js

如果想将储存的修改重新应用,首先要保证工作区与暂存区是干净的,并且当前分支是执行 git stash 所在的分支,否则会产生合并冲突。

$ git stash apply stash@{1}
On branch main
Your branch is up to date with 'origin/main'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   test.js

no changes added to commit (use "git add" and/or "git commit -a")

git stash apply 指令如果没有指定储存名字,默认是指向最后的储藏( 例子中指向 stash@{0} )。
git stash apply 指令只会重新应用储存的修改,但在内存里并未删除,可以执行 git stash drop 来删除储存的修改。

$ git stash list
stash@{0}: WIP on test1: f163bf8 test1
stash@{1}: WIP on main: c9d6d53 Update hello.js

$ git stash drop stash@{1}
Dropped stash@{1} (6770e6100eab0a62ba05c3fc53b0b94a9e2f160c)

也可以执行 git stash pop 来应用储藏并立即删除。

$ git stash pop stash@{1} 
On branch test1
Your branch is up to date with 'origin/test1'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   test.js

no changes added to commit (use "git add" and/or "git commit -a")
Dropped stash@{1} (5d53b5b7a5fce10cb347e444a6e7bd50d8919bc7)

删除分支

git branch -d <分支名>
git push -d origin <分支名> # 将删除分支同步到远程仓库

例子:

切换到其他分支,然后删除 hotfix 分支:

$ git checkout main
$ git branch -d hotfix
Deleted branch hotfix (was ca5ebf0).

图片描述

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP