5

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.

Andrew
  • 18,680
  • 13
  • 103
  • 118

3 Answers3

6

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
David Deutsch
  • 17,443
  • 4
  • 47
  • 54
4

If you're looking to undo the 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
Yoel
  • 9,144
  • 7
  • 42
  • 57
  • Note that this only applies if the commit to be reverted is the last one. Also, `--amend` only works if that commit has not already been pushed. – David Deutsch Feb 08 '16 at 21:06
1

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
jthill
  • 55,082
  • 5
  • 77
  • 137