To reset or revert a file to a specific revision in Git, use one of the following methods:
1. Reset a File to a Specific Commit
Replace the current version of the file with its state from a specific commit (e.g., abc1234
):
git checkout abc1234 -- path/to/file.txt
# OR (modern Git)
git restore --source abc1234 -- path/to/file.txt
2. Reset to the Last Commit (HEAD)
Discard local changes and revert the file to the last commit:
git checkout HEAD -- path/to/file.txt
# OR
git restore path/to/file.txt
3. Revert to a Previous Commit (Create a New Undo Commit)
If you want to preserve history and create a new commit that undoes changes:
git revert abc1234 -- path/to/file.txt
# Follow the prompts to create a new commit
4. Preview File Content from a Specific Revision
View the file’s content at a specific commit without modifying your working directory:
git show abc1234:path/to/file.txt
Key Notes
- Commit Hash: Replace
abc1234
with the actual commit hash (usegit log
to find it). - Paths: Use the correct file path (relative to the repository root).
- Staged Changes: To unstage a file and reset it, add
--staged
:
git restore --staged --source abc1234 -- path/to/file.txt
Example Workflow
- Find the target commit:
git log --oneline -- path/to/file.txt
# Example output:
# abc1234 Fix file.txt
# def5678 Update file.txt
- Reset the file to commit
abc1234
:
git checkout abc1234 -- path/to/file.txt
- Commit the reverted file:
git commit -m "Revert file.txt to commit abc1234"
Summary Table
Command | Use Case |
---|---|
git checkout <commit> -- <file> | Reset file to a specific commit (old syntax). |
git restore --source <commit> -- <file> | Reset file (modern syntax). |
git revert <commit> -- <file> | Create a new commit that undoes changes. |
git show <commit>:<file> | Preview a file’s content from a commit. |
By using these commands, you can safely revert files to previous states without affecting the rest of your repository.