5

I have done some research online, and I still could not figure out what is the best way to revert one single file that has been pushed to repository using GIT.

I have done Git Revert, but it reverts back the entire commit. So let's say if you have 2, 3 files in a commit, but you only want to revert back 1 file, that wouldn't really work well.

Any ideas? Many thanks

doglin
  • 1,651
  • 4
  • 28
  • 38
  • Very quick google search for `git revert a file` led to: [git: revert (reset) a single file](http://www.norbauer.com/rails-consulting/notes/git-revert-reset-a-single-file.html) – zedfoxus Jun 19 '15 at 14:42
  • 1
    that is for Uncommitted changes. My changes have been committed and pushed – doglin Jun 19 '15 at 14:50
  • [`git revert a file to previous version`](http://stackoverflow.com/questions/215718/reset-or-revert-a-specific-file-to-a-specific-revision-using-git) – zedfoxus Jun 19 '15 at 15:32

2 Answers2

9

Try this:

git reset HEAD~1 -- file1.txt
git checkout -- file1.txt
git commit 
git push

How it works

git reset brings the index entry of file1.txt to its state on HEAD~1 (the previous commit, the one before the wrong update). It does not modify the working tree or the current branch.

git checkout makes the working tree version of file1.txt identical with the version from the index (this is the version we need, right?)

You cannot use git commit --amend because the commit that you want to undo was already pushed to the remote repository. This is why you must create a new commit and push it.

axiac
  • 68,258
  • 9
  • 99
  • 134
2

First, revert the commit, but do not commit the revert: git revert --no-commit <SHA>. Then, unstage all the files that would be reverted with git reset. Then you can add just the files you want with git add <file>. Do a git commit, then clean up your working directory to match the index with git checkout ..

David Deutsch
  • 17,443
  • 4
  • 47
  • 54