How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?
-
possible duplicate of Revert to previous Git commit– nawfalFeb 9, 2014 at 18:45
-
8@nawfal may be a duplicate, but 'reset all changes after last commit' matches more searching criteria(words searched in google) than corresponding 'how to revert git repository'. At least for people like me who don't have English as their mother tongue :d– Shirish HerwadeAug 4, 2017 at 7:33
3 Answers
First, reset any changes
This will undo any changes you've made to tracked files and restore deleted files:
git reset HEAD --hard
Second, remove new files
This will delete any new files that were added since the last commit:
git clean -fd
Files that are not tracked due to .gitignore
are preserved; they will not be removed
Warning: using -x
instead of -fd
would delete ignored files. You probably don't want to do this.
-
9@Adam: You may sometimes want the
-x
option togit clean
as well, which directs it to remove ignored files as well.– CascabelJan 8, 2011 at 0:35 -
39If you want to keep files that are not tracked due to .gitignore, be careful with the
git clean -fd
command. Sep 23, 2014 at 13:12 -
4@Levinaris: It is the other way around
git clean -fd
will not delete ignored files.-x
will. Jan 13, 2015 at 16:14 -
7@RobertSiemer Actually, it can! If you have any folders composed entirely of ignored files it will remove those folders thus deleting ignored files. Consider a .gitignore file like the one here: stackoverflow.com/q/25554504/456645. In this example, assume some folders have no PHP files.
git clean -fd
will delete those folders and untracked files. Tested with git version 1.9.1 Jan 20, 2015 at 17:24 -
4
How can I undo every change made to my directory after the last commit, including deleting added files, resetting modified files, and adding back deleted files?
You can undo changes to tracked files with:
git reset HEAD --hard
You can remove untracked files with:
git clean -f
You can remove untracked files and directories with:
git clean -fd
but you can't undo change to untracked files.
You can remove ignored and untracked files and directories
git clean -fdx
but you can't undo change to ignored files.
You can also set clean.requireForce
to false
:
git config --global --add clean.requireForce false
to avoid using -f
(--force
) when you use git clean
.
There are two commands which will work in this situation,
root>git reset --hard HEAD~1
root>git push -f
For more git commands refer this page
-
6
git push -f
is not related to the question and, in this scenario, is dangerous Feb 11, 2020 at 22:19 -
2This will remove the last commit from the remote repository, instead of dropping all changes since the last commit. Nov 26, 2021 at 10:43
-
1Please delete this answer, it does the opposite of what the OP asked, and thus unsafe. Deleting this answer will also restore your lost rep. Sep 21, 2022 at 3:18
-
1