Git问题:切换分支后本地代码会改变吗?

2025-06-20  本文已影响0人  _百草_

1、问题

29447@GW64 /d/myProject (temp_branch)
$ git status -s
 M temp.txt
?? stash_file

29447@GW64 /d/myProject (temp_branch)
$ git checkout -
M       temp.txt
Switched to branch 'main'

29447@GW64 /d/myProject (main)
$ git status -s   # 切换main分支后,文件及状态一致
 M temp.txt
?? stash_file

29447@GW64 /d/myProject (main)
$ git add .

29447@GW64 /d/myProject (main)
$ git status -s
A  stash_file
M  temp.txt

29447@GW64 /d/myProject (main)
$ git checkout -
A       stash_file
M       temp.txt
Switched to branch 'temp_branch'

29447@GW64 /d/myProject (temp_branch)
$ git status -s   # 切换test_branch分支后,文件及状态一致
A  stash_file
M  temp.txt

2、原因

一个工作区和一个暂存区,但是存在多个分支的提交区
1、没有commit时,无论有无add,进行切换分支操作时,原分支修改的内容在新分支也有
2、已经add且commit时,切换分支操作,新分支上就看不到原分支上的修改了

29447@GW64 /d/myProject (temp_branch)
$ git status -s
A  stash_file
M  temp.txt

29447@GW64 /d/myProject (temp_branch)
$ git commit stash_file -m "test_branch:提交stash_file"
[temp_branch 4f6eb6f] test_branch:提交stash_file
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 stash_file

29447@GW64 /d/myProject (temp_branch)
$ git status -s
M  temp.txt

29447@GW64 /d/myProject (temp_branch)
$ ls
3ac_202506171610.txt  stash_file  temp.txt


29447@GW64 /d/myProject (temp_branch)
$ git checkout -
M       temp.txt
Switched to branch 'main'

29447@GW64 /d/myProject (main)
$ git status -s
M  temp.txt

29447@GW64 /d/myProject (main)
$ ls
3ac_202506171610.txt  temp.txt


3、参考

1、git切换分支后,本地代码会改变吗

上一篇 下一篇

猜你喜欢

热点阅读