且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

git:切换分支并忽略没有提交的任何更改

更新时间:2023-09-20 11:57:58

你需要一个干净的状态来改变分支。只有在不影响'脏文件'的情况下才允许分支结账(如 Charles Bailey

否则,您应该:


  • 隐藏您当前的更改或
  • reset --hard HEAD (if你不介意丢失这些微小的变化)或
  • checkout -f (当切换分支时,即使索引或工作树不同于HEAD也是如此,用于丢弃本地更改。)


I was working on a git branch and was ready to commit my changes, so I made a commit with a useful commit message. I then absentmindedly made minor changes to the code that are not worth keeping. I now want to change branches, but git gives me,

error: You have local changes to "X"; cannot switch branches.

I thought that I could change branches without committing. If so, how can I set this up? If not, how do I get out of this problem? I want to ignore the minor changes without committing and just change branches.

You need a clean state to change branches. The branch checkout will only be allowed if it does not affect the 'dirty files' (as Charles Bailey remarks in the comments).

Otherwise, you should either:

  • stash your current change or
  • reset --hard HEAD (if you do not mind losing those minor changes) or
  • checkout -f (When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes. )