Suppose I create (but do not commit) a file file.txt, and then type git checkout HEAD or git checkout HEAD .. I thought git checkout basically overwrote your current working files with the snapshot at the commit you give it, so I would have thought this would delete file.txt. But it doesn't. Why?
Why does git checkout not delete new files?
5k Views Asked by Jack M At
2
There are 2 best solutions below
0
On
git checkout doesn't overwrite your working copy by-design.
It works in the same way as git reset --hard but with the important difference - git checkout is working-directory safe, so it doesn't overwrite existing changes in your working directory. Actually, it’s a bit smarter — it tries to do a trivial merge in the working directory.
So, if you want to discard all of your changes and just get the snapshot from HEAD use git reset --hard HEAD or just git reset --hard instead.
But even git reset --hard doesn't remove your untracked files. To remove untracked files:
- Run
git clean --dry-run. It just tells you what will be removed. Do it because cleaning is a dangerous command. - Run
git clean --forceto eventually remove your untracked files.
You can find more details about git checkout and git reset here and about cleaning here.
file.txt, being untracked, is "invisible" to Git. If there is another file namedfile.txtin the commit you check out, it can be overwritten as a side effect of the check out, but Git won't go out of its way to removed untracked files.