4

I am learning git and was was surprised by the fact that staged files created while being in topic branch are not deleted when checking out to the master.

For example:

git checkout -b topic
nano newfile.txt
git add newfile.txt
git checkout master // newfile.txt is still in the working directory, even though it was created in topic branch

I am well aware of git clean command, it's just that I expected that all files that were never committed are removed if you checkout to a different branch.

Am I missing something here or is this the expected behaviour of git?

sanjihan
  • 5,592
  • 11
  • 54
  • 119
  • Try to think of that in another way: what if you loose all the changes that you actually need? You can always adjust the working directory to the staged version, but git minimizes your risk to loose unstaged changes. – Dmitry Kuzminov May 21 '19 at 18:14
  • See also https://stackoverflow.com/questions/22053757/checkout-another-branch-when-there-are-uncommitted-changes-on-the-current-branch – torek May 21 '19 at 21:26

2 Answers2

5

It is expected behaviour. If I had to describe it (and anyone is welcome to dispute my explanation), I would say that because your newfile.txt has not yet been checked in and nothing in the master branch is associated with newfile.txt yet, git should not be removing files that it is not responsible for yet. Under normal circumstances, we do not want git creeping around and modifying files that have not been added to the repo yet. On the other hand, if the file has been added to the repo, it is fair game for git to be removing changes.

That said, as you already suggested, it is possible to remove these types of files in the directory via the git clean commands.

Jason K Lai
  • 1,500
  • 5
  • 15
0

As an alternative to git clean after a checkout, you can still switch to a different branch while discarding current changes with the new (experimental) command git switch.
That would require Git 2.23 (Q3 2019)

git checkout -b topic
nano newfile.txt
git add newfile.txt
git switch -f master # newfile.txt would be gone.

That requires only one command (git switch) instead of two (checkout + clean)

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250