The multitude of answers here, including the accepted answer, always leaves me questioning which commands I should run.
Many have warnings, and despite visiting this question many times, I can never remember which combination I should, or more importantly should not, run.
So, I am leaving this here for myself when I revisit the topic next week.
git restore .
git clean -f
git clean -fd
For most scenarios you can simply combine the commands, but as I point out in my explanation some cases require you delete files first, then the directories that hold them.
git restore . && git clean -fd
Explanation:
The command git restore .
performs a checkout on the current branch to the current directory. This will undo any changes made to any files. More specifically, the command will revert all changes in tracked files to their last committed state in the current directory and subdirectories.
The command git clean -f
removes any newly added (untracked) files since the restore. This command permanently deletes files and cannot be undone.
The command git clean -fd
removes any newly added directories since the restore. This command permanently deletes directories and their files and cannot be undone.
Note: I am not a git
expert, just someone who uses git professionally, every day, all day, for many years. I advise you to consult the documenation.
With that said -fd
should take care of -f
but there are exceptions where it blows up. In my experience, executing all three commands works. It is kind of like calling Directory.Delete(path, recursive=true)
which should delete all files but sometimes for whatever reason (depending on your OS) you must delete each file first before deleting the directory.
Another Note: Misleading Warning in Accepted Answer And Other Answers: The accepted answer's warning regarding git reset ("Warning this will reset all of your unpushed commits to master!") might be misleading. git reset
without any arguments defaults to git reset --mixed HEAD
, which only affects the staging area (index) and not the working tree or commit history. git reset
does not revert commits or affect the branch history unless combined with a commit reference (like git reset --hard <commit>
), which indeed can change the commit history in the local repository.
git checkout path/to/file
will only revert the local changes topath/to/file
– Papp