Andrew February 2016

How to revert changes to 1 file in previous commit

Using SourceTree preferably or a simple git command, how would I undo the changes to 1 file in previous commit. Saying it another way, how to reverse a commit, but only for 1 of many files that were committed?

Looking to avoid having to reverse the whole commit and then recommit all but the 1 file's changes.

edit: I ended up just manually "reverting" the 1 file by editing it. But got 2 good looking answers though, I'll pick the one that appears to work in more cases.

Answers


David Deutsch February 2016

Do:

git revert <commit> --no-commit     #reverts the whole commit, putting changes in index and working dir
git reset HEAD .                    #clears index of changes
git add <fileyouwanttorevert>       #adds changes to that one file to index
git commit -m "Reverting the file"  #commits that one file's changes
git checkout .                      #gets rid of all the changes in working directory


Yoel February 2016

If you're looking to undo latest commit and it wasn't pushed yet, you may issue the following commands:

git checkout HEAD^ -- <file_path>  # revert and stage the problematic file
git commit --amend                 # edit the latest commmit


jthill February 2016

To revert the changes to a file in an arbitrary commit,

git revert $thecommit              # revert the whole commit
git reset --hard @{1}              # in what turns out to have been a throwaway commit
git checkout @{1} $thatfile        # take what you want

but if the unwanted changes are in the most recent commit you can just check out the unaltered version directly with

git checkout @^ $thatfile          # restore mainline-parent content

Post Status

Asked in February 2016
Viewed 1,546 times
Voted 9
Answered 3 times

Search




Leave an answer