Undoing an edit to the index and working copy

Let’s consider this same example, except we staged our edit this time. We then realize this specific change is irrelevant right now, and want to remove it from both the index and our working copy. We’ll go with a git checkout HEAD -- my-file. We can see the latest known version of our file from the local repo is used to overwrite both its index version and our working copy.

Again, let's try this out in the terminal.

(Example 02-undo-index-and-wd-changes)

We start from the same project as before, except this time file-3 was staged already, as git status can attest. We’ll edit file-1 and stage it too. Our goal will then be to completely undo changes to file-1. Let's do another git status for safety.

As you can see, once again git status helps us with advice about unstaging files, telling us to “use "git reset HEAD <file>..." to unstage”. We’ll look into that in a moment. What you must remember for now is that such a reset would only unstage, but not restore our working copy. We would have to use a checkout afterwards anyway.

Let’s instead kill two birds with one stone by going with just a git checkout HEAD -- file-1. Again, git status lets us verify that this worked, as the file doesn’t show up anymore, be it as staged in the index, or as modified in the working copy. Looking at the file-1 we can confirm our edit isn’t there anymore.

“Git undo” or the art of rolling back

Relax! Git makes it easy to get back seemingly lost work and dig yourself out of even the most delicate situations.

Already enrolled?
Sign in to continue learning.