Git 切换分支,将当前分支的修改带到下个分支

使用刚初始化的 git 项目进行开发时,切换分支的时候发现 dev 分支的修改带到了 master分支。

1、出现原因

原因在于 dev 分支拥有与 master相同的 commit 历史,git此时会带着当前分支的修改到下个分支中,通过 git log可查看 commit历史。

1.1、例子

我现在本地拥有 devmaster分支,修改了 dev分支上的 **application.properties **文件,此时git checkout master切换到master分支,有以下提示

# 切换到master,提示application.properties已经修改
D:\WebTeam\MyBatis_Plus\mybatis_plus>git checkout master
Switched to branch 'master'
M       src/main/resources/application.properties
Your branch is up to date with 'origin/master'.

此时在 master 分支可以看到已经修改了的 application.properties 文件。

执行 git log可以看到 dev分支与 master相同的commit历史,当然只有在初始化项目时 dev分支才会拥有与master一样的 commit历史,后面一般在dev分支进行 commit,再合并到master

Git 切换分支,将当前分支的修改带到下个分支

2、Please commit your changes or stash them before you switch branches.

当在dev分支做了修改,而且dev分支与master分支的commit历史不一致,想切回master分支时就会有 Please commit your changes or stash them before you switch branches. 提示,翻译过来的意思是“在你切换分支之前请先提交你的修改或者暂存他们”。

Git 切换分支,将当前分支的修改带到下个分支

因此想要切换分支就需要用到git commit命令或者git stash命令。

2.1、不应用当前分支的修改,单纯地切换分支

很多时候我们并不想提交,只是想单纯的切换分支,不想把修改带到切换的分支,那就使用git stash保存工作区和暂存区的修改到堆栈中,就可以切换到master分支了,当切回dev分支时再执行git stash pop取回原先的修改就可以了。执行命令如下;

# 保存dev分支的修改到堆栈中
$ git stash

# 切换master分支
$ git checkout master

# 切回dev分支
$ git checkout dev

# 获取堆栈列表
$ git stash list

# 取回堆栈最新的修改
$ git stash pop

2.2、应用当前分支的修改到切换的分支中

由于 git stash的堆栈是所有分支共享的,所以 master分支也可以取得dev分支的修改,过程非常的简单。

# 保存dev分支的修改到堆栈中
$ git stash

# 切换master分支
$ git checkout master

# 取回堆栈最新的修改
$ git stash pop

# 或者取回堆栈指定的修改
$ git stash apply stash@{0}

参考博客:当前分支的修改带到下个分支中

相关文章:

  • 2022-12-23
  • 2022-02-05
  • 2021-09-26
  • 2022-02-06
  • 2021-09-20
  • 2021-11-14
  • 2021-11-27
猜你喜欢
  • 2021-10-19
  • 2021-12-05
  • 2021-04-04
  • 2022-03-07
  • 2022-12-23
  • 2021-04-18
  • 2022-12-23
相关资源
相似解决方案