Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo part of unstaged changes in git

Tags:

git

How do I undo parts of my unstaged changes in git but keep the rest as unstaged? The way I figured out is:

git commit --interactive
# Choose the parts I want to delete
# Commit the changes
git stash
git rebase -i master # (I am an ancestor of master)
# Delete the line of the most recent commit
git stash apply

This works, but it would be nice if there were something like git commit --interactive only for reverting changes. Any better methods?

like image 873
asmeurer Avatar asked Oct 13 '22 08:10

asmeurer


People also ask

How do you undo uncommitted changes 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.


2 Answers

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.

$ git checkout -p file/to/partially/revert
# or ...
$ git checkout -p .

If you wish to snapshot your git repository beforehand to preserve these changes before reverting them, I like to do:

$ git stash; git stash apply

If you use that often, you might want to alias it:

[alias]
    checkpoint = !git stash; git stash apply

Reverting individual hunks or lines can be even easier if you use a good editor mode or plugin, which may provide support for selecting lines directly to revert, as -p can be a bit clumsy to use sometimes. I use Magit, an Emacs mode that is very helpful for working with Git. In Magit, you can run magit-status, find the diffs for the changes that you want to revert, select the lines you wish to revert (or simply put the cursor on hunks you wish to revert if you want to revert a hunk at a time instead of a line at a time), and press k to revert those specific lines. I highly recommend Magit if you use Emacs.

like image 297
Brian Campbell Avatar answered Oct 22 '22 22:10

Brian Campbell


git diff > patchfile

Then edit the patchfile and remove the parts you don't want to undo, then:

patch -R < patchfile
like image 33
octoberblu3 Avatar answered Oct 22 '22 23:10

octoberblu3