Skip to main content

Why Sometimes git checkout fails

Did you ever wonder why when you run git checkout <branch name> from say a feature branch to the main branch it will fail? Well there could be many reason, the primary reason is that you have some local changes that you didn't commit / stash before switching to the other branch, which can result in those changes in being lost.

This is why Git is trying to warn you when you get the message like this:

error: Your local changes to the following files would be overwritten by checkout:
        player-2
Please commit your changes or stash them before you switch branches.
Aborting
But sometimes this doesn't happen?

git checkout will sometimes work if you have some uncommitted changes, but when?

Well if you spawn off a branch and you make some local changes WITHOUT committing them, because the git history between the two branches are the same, you are free to switch between and carry those changes between the two branches without getting the error.

It also work with new untracked files that you have created, because they are technically not part of the index / history, so you can switch between branches and carry those changes

However, if you committed some changes to the branch on a particular file, making the two branches not aligned anymore and then you try to carry some changes to the other branch then Git will stop you from doing so, if it is regarding the same file that was committed.

It doesn't matter which side it is from, if you're on master and spawned off feature-a branch.

  • Say you committed to master one commit and you edited the same file on feature-a without committing, and want to checkout master, it will prevent you from doing so
  • Say you committed to feature-a one commit and you edit the same file on master without committing, and want to checkout feature-a, it will prevent you from doing so

It is regarding the same file that was committed, this is because the local change from the branch will be overwritten making you lose your changes!