doglin
doglin

Reputation: 1741

How to revert a single committed file that has been pushed in GIT?

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

Upvotes: 8

Views: 11553

Answers (2)

axiac
axiac

Reputation: 72356

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.

Upvotes: 9

David Deutsch
David Deutsch

Reputation: 19035

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 ..

Upvotes: 1

Related Questions