1

I faced this problem working on my fork of a repository. When I would make changes to some file(s) on a new branch and then switch to a different branch, git will not raise the error: You have local changes to "X"; cannot switch branches. error. Instead, it will just move to the new branch and reflect the changes in that branch as well. Please let me know if this a beginner mistake on my part.

Steps to reproduce -

  • Fork the repository
  • git checkout -b new-branch-name
  • Make changes to any file
  • Switch back to master and those changes would reflect there

This is causing my master to be the same as a branch that I made changes to, which continued to stay after. Committing once to the newly created branch, however, fixes this issue.

nishd
  • 21
  • 1
  • 4

1 Answers1

4

The reason you're seeing this is because you haven't committed the changes. You've edited the working copy and possibly run git add, but haven't run git commit.

Git will let you check out another branch with changes in the working copy provided it can preserve those changes. For example, if you've changed a file and that file is the same in both branches, Git doesn't need to change the file during checkout, and so it will preserve the version in your working tree. This makes it much easier if you realize you're accidentally on the wrong branch or need to make a new topic branch.

If you want to preserve your changes on a branch, you need to commit them; Git won't track them as part of that branch otherwise. Simply making changes to the working copy with a given branch checked out doesn't preserve them in any way.

If your working tree is clean (that is, it has no uncommitted changes), git checkout will completely change the state of your working tree to another branch.

bk2204
  • 64,793
  • 6
  • 84
  • 100