Question

Before committing, I see with git diff that I've made a change that I would rather not have made. Is there any way to revert this single change?

I suppose that I could use git add -p to commit the changes that I did intend to make, and then to checkout master. Is there a better way, preferably a way that does not require me to commit?

This is with Git 1.7.10.4 on Kubuntu Linux 12.10. Thanks!

Was it helpful?

Solution

git reset --patch (or git reset -p) does what you want.

The relevant bit of the documentation:

git reset (--patch | -p) [] [--] […]

Interactively select hunks in the difference between the index and (defaults to HEAD). The chosen hunks are applied in reverse to the index.

This means that git reset -p is the opposite of git add -p, i.e. you can use it to selectively reset hunks. See the “Interactive Mode” section of git-add(1) to learn how to operate the --patch mode.

Note that git reset (applied on paths) does match git add — the latter stages files or chunks while the former unstages them, and so git reset supports the --patch option just like git add does.

You might also be interested to learn about git checkout --patch (or git checkout -p).

OTHER TIPS

git checkout also has -p option which is, basically, the same as -p in git add, but in reverse.

Just do:

git checkout -p <path>

(or without path if you want)

Like with git add -p you choose which changes to stage, here you choose which changes to revert.

I have no silver bullet to submit, but when I have such a use case, I go with git gui. I just index all the changes I need then revert unwanted changes.

That's the same as a git add -p, but git gui makes the operation really neat.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top