Git Restore All Unstaged Files Back to their Latest Commit
From time to time, you may want to test some changes locally within a git repository, but you do not want to push them upstream.
While doing so, a quick git status
, you can see a combination of various changes made to files and directories.
- Which files or directories are new and aren’t in version control yet?
- Are those changes currently staged or unstaged to be committed?
- What changed since their last commit?
Using this information, we can answer the following questions in this post:
- How can I unstage and revert a specific file back to its latest upstream version?
- How can I revert all unstaged changes back to their latest upstream version?
- How can I delete all files and directories that aren’t tracked?
I assume that you haven’t committed anything and just want to revert your changes locally.
Cleaning up
Unstage and Revert a File
One basic thing we can do is to restore a file that was staged before and restore it to its latest committed state.
1git restore --staged $FILE
2
3git restore $FILE
Note: Executing commands like this is destructive. If your file isn’t already staged, then you only need to run git restore $FILE
.
Restore All Tracked Files Back to Their Latest Committed State
This part is not much different from our previous point, except that here we replace all files and directories recursively.
1git restore --staged .
2git restore .
Note: If the files aren’t staged, you only need to run git restore .
.
Delete All Untracked Files and Directories
Unlike the previous steps, we cannot use git restore here because there is nothing to restore. But we have a couple of options depending on your use case:
1# Only perform a dry run.
2
3git clean --dry-run
4
5# Include directories.
6
7git clean --dry-run -d
8
9# Perform an interactive delete.
10
11git clean --interactive -d
12
13# Force delete everything.
14
15git clean --force -d
16
17# Force delete files that are only ignored by git.
18
19git clean --force -X
Note: Running git clean --help
to see what else exists.
Sources
- Git clean - https://git-scm.com/docs/git-clean