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?
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 --force
to 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 named file.txt
in 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.
git checkout .
or git checkout <ref>
? I was describing the latter. –
Germander git checkout HEAD .
- if I just do git checkout HEAD
it doesn't do anything, but it doesn't give me an obvious error either (it prints out a message about the modification to the file, though, which I guess is what you mean). –
Titty Try
git clean -fd
This has been bothering me for a long time. Finally found that the command above will delete untracked files/folders.
BTW, you still need
git checkout -- .
to discard all local changes.
© 2022 - 2024 — McMap. All rights reserved.
git checkout
does not affect untracked files. – Germandergit checkout
will still modify files that differ from how they were in the last commit, even if you haven't staged those changes. – Tittygit status
. You'll see the new file in the "Untracked files" section. – Germandergit checkout
, so what's in the index right now are those that were in the snapshot. But if you change the index (withgit rm --cached
orgit add
, for instance), that changes the set of tracked files. Note also thatgit checkout <tree-ish> <paths>
is a very different command fromgit checkout <branch>
. Some (including myself) believe it should use a different spelling, i.e., not start withgit checkout
at all. – Ianteengit checkout
behaves so wildly differently :) – Germandergit clean
, i've corrected my answer below. – Reciprocity