git: Switch branch and ignore any changes without committing

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

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.

回答1:

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


回答2:

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 


回答3:

well, it should be

git stash save git checkout branch // do something git checkout oldbranch git stash pop 


回答4:

Follow,

$: git checkout -f  $: git checkout next_branch 


回答5:

If you have made changes to files that Git also needs to change when switching branches, it won't let you. To discard working changes, use:

git reset --hard HEAD 

Then, you will be able to switch branches.



回答6:

Note that if you've merged remote branches or have local commits and want to go back to the remote HEAD you must do:

git reset --hard origin/HEAD 

HEAD alone will only refer to the local commit/merge -- several times I have forgotten that when resetting and end up with "your repository is X commits ahead.." when I fully intended to nuke ALL changes/commits and return to the remote branch.



回答7:

switching to a new branch losing changes:

git checkout -b YOUR_NEW_BRANCH_NAME --force 

switching to an existing branch losing changes:

git checkout YOUR_BRANCH --force 


回答8:

Close terminal, delete the folder where your project is, then clone again your project and voilá.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!