1

I'm confused with an encountered Git behaviour - when I edit some stuff and checkout to another branch (e.g. master), I get:

M       some_script.py
Switched to branch 'master'

The file stays modified, and I can commit it on the second branch.

What's the reason of such a behaviour, how I turned that on (I'm used to being forced to stash the changes), and how to avoid it?

maciejwww
  • 1,067
  • 1
  • 13
  • 26
  • 2
    `What's the reason of such a behaviour?` The reason for this is among other things imagine you are working on branch `some_feature` and while modifying `some_file.txt` you realize that the changes you are currently doing is not directly related to `some_feature`. Git then allows you to check out a different (possibly new) branch where you commit (possibly parts of) the current changes before switching back to `some_feature`. – hlovdal Mar 12 '23 at 16:10
  • 1
    True, that's an important feature. – maciejwww Mar 12 '23 at 19:42
  • https://stackoverflow.com/a/67453215/341994 – matt Apr 03 '23 at 14:57

1 Answers1

4

This is the default, correct behavior of Git.

When performing a git checkout <branch> or git switch, local changes and the index are preserved; however, if there is a conflict between your local changes, and changes made on the target branch, you will be prevented from checking out the target branch.

This is the error message you're most likely familiar with:

error: Your local changes to the following files would be overwritten by checkout

As per the documentation:

Switching branches does not require a clean index and working tree (i.e. no differences compared to HEAD). The operation is aborted however if the operation leads to loss of local changes, unless told otherwise with --discard-changes or --merge.

TonyArra
  • 10,607
  • 1
  • 30
  • 46