Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git undo partial changes to a file

Tags:

git

undo

merge

How do I undo a part of the changes applied to a file that happened a while a go. I have the following commits and the accidental changes happened between A and B to 'file.txt'

...--A--B--...

I have a diff patch of the file in file.txt-B-A.patch which reverts all changes. However I only want to undo certain changes in file.txt, much like manually picking changes in a merge conflict. Is there a way to do so without modifying the patch file?

like image 857
camillobruni Avatar asked Mar 21 '13 13:03

camillobruni


People also ask

How do I undo a specific change in git?

Try Git checkout --<file> to discard uncommitted changes to a file. Git reset --hard is for when you want to discard all uncommitted changes. Use Git reset --hard <commit id> to point the repo to a previous commit.

How do I revert to a previous version of a file in git?

You previously saw how to use git checkout to undo the changes that you made since the last commit. This command can also be used to go back even further into a file's history and restore versions of that file from a commit.


2 Answers

Many git commands have the -p option ("patch") or -i ("interactive") to do something partially. For arbitrary diffs I don't think this is supported, but you can apply the patch and then selectively undo unstaged changes using git checkout -p -- <path(s)>, e.g. git checkout -p -- . if you're at the top level of the repo.

like image 106
Jan Krüger Avatar answered Sep 30 '22 10:09

Jan Krüger


There's another way to do this that doesn't require the patch file at all.

The problem happened going from A to B, so first revert the changes in B but don't automatically commit.

$ git revert --no-commit <commit hash of B>

The changes that git revert would do are staged. Unstage them.

$ git reset HEAD

Next, interactively go through file.txt and stage only the changes you want to keep.

$ git add --patch file.txt

Only the reverts you selected are now staged. Commit them.

$ git commit

Finally, clean up the unstaged leftovers from git revert.

$ git reset --hard
like image 20
Rob Bajorek Avatar answered Sep 30 '22 08:09

Rob Bajorek