Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 714
doglin Avatar asked Feb 10 '23 19:02

doglin


2 Answers

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.

like image 79
axiac Avatar answered Feb 13 '23 04:02

axiac


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

like image 34
David Deutsch Avatar answered Feb 13 '23 02:02

David Deutsch