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

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切换分支后,本地代码会改变吗

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容