How to revert a single file in Git

Published on Aug. 22, 2023, 12:16 p.m.

To revert a single file in Git, you can use the git checkout or git reset command. Here are the steps to revert a single file:

  1. Use git log to find the commit hash of the version of the file you want to revert to:
git log myfile.txt
  1. Use git checkout to revert the file to the version in the desired commit:
git checkout <commit-hash> myfile.txt

This will replace the contents of myfile.txt with the version in the specified commit, leaving other files in the working directory untouched.

Alternatively, you can use git reset to revert the file to the version in the desired commit while preserving the changes as unstaged changes:

git reset <commit-hash> -- myfile.txt

This will keep the changes you made to other files, but create unstaged changes for myfile.txt that reflect the differences between its version in the specified commit and the version in your latest commit.

If you want to completely remove all changes to the file and restore it to its state in the specified commit, you can additionally use git add and git commit to stage and commit the changes made by git reset:

git add myfile.txt
git commit -m "Revert myfile.txt to commit <commit-hash>"

Tags:

git