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.
Can I 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 can pass the -f or --force option with the git checkout command to force Git to switch branches, even if you have un-staged changes (in other words, the index of the working tree differs from HEAD ). Basically, it can be used to throw away local changes.
Here is how to save local changes without commit in Git. Just issue git stash command as shown below from your present working directory which contains unsaved unchanges. This will stash all changes you made and your repository will be restored to your last commit.
Take away: changing branches does not touch/change/remove untracked or checked in files. Remember that the working directory and index are not 'cleared' before the branch content is loaded into it!
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:
reset --hard HEAD
(if you do not mind losing those minor changes) orcheckout -f
(When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes. )Or, more recently:
git switch
:git switch -f <branch-name>
-f
is short for --force
, which is an alias for --discard-changes
)Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
This differs from git switch -m <branch-name>
, which triggers a three-way merge between the current branch, your working tree contents, and the new branch is done: you won't loose your work in progress that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With