Switching a branch after aborting current changes

2019-03-08 14:05发布

问题:

I cloned a git repo and then started playing around in its master branch. After a while, I want to ignore the changes I just made (without committing them), and switch to a different branch. However, it stops me from switching because there are uncommitted changes. How do I ignore them without stashing them either? This is what happens:

$ git checkout gh-pages
error: Your local changes to the following files would be overwritten by checkout:
        somefile.txt
Please, commit your changes or stash them before you can switch branches.
Aborting

回答1:

Option 1

git checkout -f gh-pages

Option 2

git reset --hard     # beware: don't make that a habit
git checkout gh-pages


回答2:

Just for the sake of completeness, and for those who landed here by searching: Although the OP asks specifically for a solution without stashing, it is worth mentioning that stash is indeed a very nice option:

The command saves your local modifications away and reverts the working directory to match the HEAD commit.

So you can simply

git stash

This is like resetting to HEAD. When being absolutely positively certain that indeed those uncommitted changes are worthless, simply

git stash drop

You can even have multiple stashes etc. as mentioned in the documentation link above.

I would recommend this practice since it puts one in the habit to double-think before resetting without a significant cost.



回答3:

You can ignore all uncommitted changes.

git reset --hard HEAD



回答4:

If you're really sure that you want to throw away your uncommitted changes (i.e. those that are staged as well as those in your working tree) you can do:

git reset --hard

In general, stashing is often safer



回答5:

If you have unstaged file, try:

git checkout -- .

Or

git checkout -- filename


回答6:

git add -A git stash

this will clear all the changes you made (Only those that are not commited)



回答7:

You can discard changes you made in a specific file:

git checkout somefile.txt

And then jump smoothly to the branch:

git checkout gh-pages