Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does git checkout not delete new files?

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?

like image 820
Jack M Avatar asked Aug 27 '18 17:08

Jack M


People also ask

Does git checkout delete?

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.

Does git checkout delete local files?

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).

How do I force delete a file in git?

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.

Does git checkout update files?

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.


2 Answers

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.

like image 179
Andrew Prigorshnev Avatar answered Sep 24 '22 16:09

Andrew Prigorshnev


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.

like image 42
chepner Avatar answered Sep 24 '22 16:09

chepner