How to git reset --hard a subdirectory?
With Git 2.23 (August 2019), you have the new command git restore
(also presented here)
git restore --source=HEAD --staged --worktree -- aDirectory
# or, shorter
git restore -s@ -SW -- aDirectory
That would replace both the index and working tree with HEAD
content, like an reset --hard
would, but for a specific path.
Original answer (2013)
Note (as commented by Dan Fabulich) that:
-
git checkout -- <path>
doesn't do a hard reset: it replaces the working tree contents with the staged contents. -
git checkout HEAD -- <path>
does a hard reset for a path, replacing both the index and the working tree with the version from theHEAD
commit.
As answered by Ajedi32, both checkout forms don't remove files which were deleted in the target revision.
If you have extra files in the working tree which don't exist in HEAD, a git checkout HEAD -- <path>
won't remove them.
Note: With git checkout --overlay HEAD -- <path>
(Git 2.22, Q1 2019), files that appear in the index and working tree, but not in <tree-ish>
are removed, to make them match <tree-ish>
exactly.
But that checkout can respect a git update-index --skip-worktree
(for those directories you want to ignore), as mentioned in "Why do excluded files keep reappearing in my git sparse checkout?".
According to Git developer Duy Nguyen who kindly implemented the feature and a compatibility switch, the following works as expected as of Git 1.8.3:
git checkout -- a
(where a
is the directory you want to hard-reset). The original behavior can be accessed via
git checkout --ignore-skip-worktree-bits -- a