假设我编辑了一个文件
echo "hi" > someVersionedFile.txt
//Then I staged the file
git add .
git status
<console reads>
Changes to be committed
new file: someVersionedFile.txt
现在我对文件进行额外的修改
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
问题:如何还原上一个暂存版本?这可能是因为它没有提交吗?
最佳答案
您可能可以做到这一点,但没有一个简单的命令可以为您做到这一点。
当你执行 git add
时,文件已经添加到存储库中,但目前除了索引之外没有任何指向它的东西。当你执行第二个 git add
时,新的(版本的)文件被添加到存储库中,索引和文件的第一个版本之间的链接被新链接替换。但是第一个对象仍然存在。
您可以使用 git fsck --dangling
获取存储库中当前未被任何内容引用的 blob 对象列表,但您必须逐一检查它们git show
、git cat-file
等来判断哪个是你要的文件。找到正确的文件后,您可以 git show HASH > somefile.txt
(也可以 git add somefile.txt
)。
当然,如果你在第二次git add
之后做过任何git prune
、git gc
等,那可能有实际上从您的存储库中删除了原始文件。
这是一个简单的例子:
$ 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
$
关于git - 如何恢复已暂存文件的更改,将更改保留到暂存时的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17659553/