git: Switch branch and ignore any changes without committing

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

Or, more recently:

  • With Git 2.23 (August 2019) and the new command 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 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

well, it should be

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

Follow,

$: git checkout -f

$: git checkout next_branch