git: Switch branch and ignore any changes without committing

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. )

  • If you want to discard the changes,

    git checkout -- <file>
    git checkout branch
    

    If you want to keep the changes,

    git stash save
    git checkout branch
    git stash pop
    

    好吧,应该是

    git stash save
    git checkout branch
    // do something
    git checkout oldbranch
    git stash pop
    
    链接地址: http://www.djcxy.com/p/4278.html

    上一篇: 我如何强制git pull覆盖每次拉动的所有内容?

    下一篇: git:切换分支并忽略没有提交的更改