Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git Diff - How do I revert selected lines or chunks

Tags:

git

diff

git-gui

In Git GUI I can select parts of a diff and stage just those lines or chunks. How would I do the opposite, as in roll back changed lines in a file. Usually these are accidental white space changes I just want to revert out but still stage/commit other parts of the same file.

like image 532
Kenoyer130 Avatar asked May 31 '12 01:05

Kenoyer130


People also ask

How do I revert part of a file in git?

You can use git checkout -p , which lets you choose individual hunks from the diff between your working copy and index to revert. Likewise, git add -p allows you to choose hunks to add to the index, and git reset -p allows you to choose individual hunks from the diff between the index and HEAD to back out of the index.

How do I see changes in git diff?

You can run the git diff HEAD command to compare the both staged and unstaged changes with your last commit. You can also run the git diff <branch_name1> <branch_name2> command to compare the changes from the first branch with changes from the second branch. Order does matter when you're comparing branches.


1 Answers

Stage the parts you want with git add -p, then discard (git checkout -- filename) the unstaged changes.

Update for Git 1.6.5+

In version 1.6.5, Git learned to checkout with a -p/--patch flag. You can discard chunks in one step with git checkout -p -- filename.

From the docs:

Interactively select hunks in the difference between the <tree-ish> (or the index, if unspecified) and the working tree. The chosen hunks are then applied in reverse to the working tree (and if a <tree-ish> was specified, the index).

This means that you can use git checkout -p to selectively discard edits from your current working tree.

like image 158
ellotheth Avatar answered Sep 28 '22 12:09

ellotheth