How to you revert a staged file with changes, preserving the changes to when it was staged?

git

Solution

You can probably do this, but there's no single simple command to do it for you.

When you do `git add`, the file has already been added to the repository, but there is currently nothing pointing to it except the index. When you do a second `git add`, the new (version of the) file gets added to the repository, and the link between the index and the first version of the file is replaced with the new link. But the first object is still there.

You can use `git fsck --dangling` to get a list of blob objects in your repository that are currently not referenced by anything, but then you'll have to go through them one by one with `git show`, `git cat-file`, etc. to determine which is the file you want. Once you find the right file, you can `git show HASH > somefile.txt` (and maybe `git add somefile.txt`).

Of course, if you've done any `git prune`, `git gc`, etc. since the second `git add`, that may have actually removed the original file from your repository.

Here's a quick example:

$ git init foo
Initialized empty Git repository in foo/.git/
$ cd foo
$ echo blah > foo.txt
$ git add foo.txt
$ echo blarg > foo.txt
$ git add foo.txt
$ git fsck --dangling
Checking object directories: 100% (256/256), done.
dangling blob 907b308167f0880fb2a5c0e1614bb0c7620f9dc3
$ git show 907b308167f0880fb2a5c0e1614bb0c7620f9dc3
blah
$

Problem

Say I edited a file ``` echo "hi" > someVersionedFile.txt //Then I staged the file git add . git status <console reads> Changes to be committed new file: someVersionedFile.txt ``` Now I make additional changes to the files ``` echo "hi again file" >> someVersionedFile.txt //Then I restage the file with these changes git add . git status <console reads> Changed but not commited modified file: someVersionedFile.txt ``` Question: how do I revert the last staged version? Is this possible to do since it wasn't committed?

Original source