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?
If nothing (or --no-recurse-submodules ) is used, submodules working trees will not be updated. Just like git-submodule[1], this will detach HEAD of the submodule. In the default overlay mode, git checkout never removes files from the index or the working tree.
git checkout does not affect untracked files. Git only manages tracked files, and it works fairly hard to avoid letting you lose data (which is critical).
The easiest way to delete a file in your Git repository is to execute the “git rm” command and to specify the file to be deleted. Note that by using the “git rm” command, the file will also be deleted from the filesystem.
The git checkout command lets you navigate between the branches created by git branch . Checking out a branch updates the files in the working directory to match the version stored in that branch, and it tells Git to record all new commits on that branch.
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:
git clean --dry-run
. It just tells you what will be removed. Do it because cleaning is a dangerous command.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With