如何撤销 'git checkout -f' 以恢复未提交的更改

4
我不小心输入了git checkout -f,因为我试图恢复已删除的文件,但现在所有未提交的文件都消失了...那是一整天的工作...有办法把它找回来吗?谢谢。

1
git fsck 会输出什么信息呢?也许其中有一些可以供您参考的内容。请注意,如果您的文件已经被暂存但未提交,则此命令将有所帮助;如果它们未被暂存,则它们几乎无法找回。 - Makoto
1
“git reflog” 只能提供已经提交的内容。如果更改未提交,则在 reflog 中将没有任何内容。 - Jon L
1
你是对的@JonL; 我在想git fsck。如果文件被暂存,那会有帮助的。 - Makoto
@Makoto 虽然花了一些时间,但最终我得到了一堆悬空的提交/文件块。 - ssgao
3个回答

6

你想要完成这个任务,成功的几率非常小,就像坐在地狱之门外的雪球一样,但它关键在于一个非常重要的步骤。

之前必须运行过git add命令来添加这些文件。

否则,你将会度过一个不愉快的时光。没有运行过git add命令,是无法找回文件的。

如果你之前运行过git add命令,那么你可以运行git fsck --lost-found来恢复任何已删除的文件。虽然你不能得到确切的文件名,但可以得到与之关联的提交blob。

makoto@LATLON-Undefined:~/Desktop/smoketest$ echo "Goodbye file" > badfile.txt
makoto@LATLON-Undefined:~/Desktop/smoketest$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    badfile.txt

nothing added to commit but untracked files present (use "git add" to track)
makoto@LATLON-Undefined:~/Desktop/smoketest$ git add .
makoto@LATLON-Undefined:~/Desktop/smoketest$ git reset --hard HEAD
HEAD is now at 7124f25 Initial
makoto@LATLON-Undefined:~/Desktop/smoketest$ git status
On branch master
nothing to commit, working directory clean
makoto@LATLON-Undefined:~/Desktop/smoketest$ git fsck --lost-found
Checking object directories: 100% (256/256), done.
dangling blob 4a503984f4847abd45f4d795d1b74c6482164dcb

这些Blob没有任何与其相关的文件信息,也就是说,它们没有文件名。但它们仍然是您的数据。

取决于您手头的情况,您可以选择以下两种方式之一:

  • Enter into each dangling blob and manually try to derive the file name for it, or
  • In reference from this site, you could experiment with their Bash script to pull in all dangling blobs and place them into your current directory with their hash as the file name.

    I haven't personally tested this script, but he does show a video of it working.

    for blob in $(git fsck --lost-found | awk '$2 == "blob" { print $3 }');
        do git cat-file -p $blob > $blob.txt;
    done
    

你不需要亲自保存悬挂的Blob,--lost-found会为你保存到.git/lost-found/other中。 - wisbucky
@wisbucky:请记住,我是从另一个网站上引用它作为示例。如果你有其他方法,我鼓励你在这里单独回答。 - Makoto

1

你是否有一个跟踪文件修改的备份系统?你可以从那里恢复它。否则你就没办法了 - 更频繁地提交代码吧!


1

两个选项:

  1. Check the git stash to see if you had stashed any of those files previously:

    git stash list
    git stash show stash@{0}
    
  2. If you had added/staged the files previously, you can try git fsck --lost-found. Git will save all the dangling blobs to ./git/lost-found/other directory (although they will not have their original filenames).


谢谢!谢谢!谢谢!我不小心检出了一些未暂存的更改,但是按照你建议的使用 git fsck --lost-found 找到并恢复了这些更改。我永远感激你。 - Caleb Koch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接