Git. Undo staged changes in working directory, keeping staged area untouched

375 views Asked by At

Suppose I have staged a few changes:

$ git diff --cached # few changes are stashed

+ change 1 new
  blabla
- change 2 old
+ change 2 new
  blabla
- change 3 old
+ change 3 new
  blabla

$ git diff  # no other changes

Now I would like to test my program quickly without change 2. With git reset head -p; git stash I can rid of change 2 completely. But I don't want to unstage it, this is just a test, I still want to commit it later on. Therefore I would like to make the changes opposite to the changes from change 2 in my working directory. The result should be like this:

$ git diff --cached # 1-3 changes are stashed

+ change 1 new
  blabla
- change 2 old
+ change 2 new
  blabla
- change 3 old
+ change 3 new
  blabla

$ git diff  #change 2 is undone

  change 1 new
  blabla
+ change 2 old
- change 2 new
  blabla
  change 3 new
  blabla

How do I achieve this?

1

There are 1 answers

2
Wes Hardaker On BEST ANSWER

One of your biggest problems comes from the fact that if your changes are independent(ish), then you should probably commit them independently first and treat them as three different commits. IE, use git commit --interactive (or git add --interactive) to commit your changes in 3 change commits instead of 1. That lets you much more easily revert one (like #2) using git revert, or other change-management magic to deal with just the commit you're looking for in question.