gitbranchgit-checkout

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.

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.


Solution

  • 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:

    Or, more recently:

    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: you won't lose your work in progress that way.