Git: Revert an Updated File

Git: Revert an Updated File


git git-revert
Last updated on

Sometimes, a file gets updated unintentionally — like when you run bundle install or yarn install, and suddenly your lock file changes. Keeping dependencies up to date is good practice, but these unrelated updates don’t belong in your feature branch.

So how do you remove such a file from your pull request without deleting it?


1. If you have not committed the changes

You can simply revert the file to its last committed state:

git checkout -- filename

Or, with the modern syntax:

git restore filename

2. If you want a partial revert

To reset a file to its state 2 commits ago:

git checkout HEAD~2 filename
# or modern equivalent
git restore --source=HEAD~2 filename

To apply the version of a file from a specific commit:

git show <commit> -- <filename> | git apply -R

3. If you already committed and pushed

If you’ve pushed changes upstream but want to undo them:

git checkout origin/<branch> -- <filename>
git commit -m "Reverted changes made to the file"

Or, with the modern git restore:

git restore --source=origin/<branch> filename
git commit -m "Reverted changes made to the file"

Quick Comparison: Old vs New Commands

ScenarioLegacy (git checkout)Modern (git restore)
Discard uncommitted changesgit checkout -- filegit restore file
Revert to specific commitgit checkout <commit> -- filegit restore --source=<commit> file
Revert to origin branch versiongit checkout origin/main -- filegit restore --source=origin/main file

Editor’s Note

When this post was first written, git checkout was the go-to command for everything: switching branches, discarding changes, and reverting files. Today, Git recommends using git restore (for files) and git switch (for branches), which make commands clearer and reduce accidental mistakes.

That said, you’ll still see git checkout in tutorials, StackOverflow answers, and older workflows, so it’s useful to understand both.


Resources


You might also like

© 2025 Syed Aslam