February 16, 2025
O. Wolfson
When working with Git, it is common to modify files and later realize that you need to discard the changes and return a file to its last committed state. This is where the git restore command proves to be an invaluable tool.
git restore Do?The command:
bashgit restore <file>
Restores the specified file(s) in the working directory to their state from the last commit. This effectively discards any uncommitted changes to the file(s).
git restore pulls the file's contents from the last committed version in the current branch.git restore <file> is a quick solution.bashecho "New content" > hello.txt
# You realize you want the original version back
git restore hello.txt
This restores hello.txt to the state from the last commit.
If you have already staged the file using git add, but wish to remove it from staging:
bashgit restore --staged hello.txt
This unstages the file, but keeps your changes in the working directory.
To restore both the working directory and unstage the file in one go:
bashgit restore --staged --worktree hello.txt
Or using shorthand:
bashgit restore -S -W hello.txt
| Command | Effect |
|---|---|
git restore <file> | Discard changes in working directory |
git restore --staged <file> | Unstage file, keep changes in working directory |
git restore --staged --worktree <file> | Unstage file and discard changes in working directory |
You can use git restore along with a commit hash to restore a single file to its state from a previous commit. Here’s how:
bashgit log
This will show a list of commits. You can find the hash of the commit you want to restore from.
Alternatively, you can directly reference say three commits back from the current HEAD like this:
bashHEAD~3
bashgit restore --source=HEAD~3 -- path/to/file.txt
This will restore path/to/file.txt to its state from three commits back (i.e., HEAD~3), in your working directory.
bashgit add path/to/file.txt
This doesn't affect other files—it only restores the specified file.
If you don't want to stage it after, you can skip git add.
You can use a commit hash instead of HEAD~3 like this:
bashgit restore --source=<commit-hash> -- path/to/file.txt
The git restore command is a simple yet powerful tool to revert individual files to their last committed state without affecting other parts of your working tree. Knowing how to use it effectively can save time and prevent mistakes in your version control workflow.