执行git reset --hard后如何恢复已暂存但未提交的文件?
Absolutely—you can get those files back! When you ran git add ., Git already converted all your files into blob objects and stored them in its local database. The git reset --hard just wiped out the references in your staging area and working directory, but those underlying objects are still there (until Git runs garbage collection, which it doesn't do automatically right away).
最快的方法:找到暂存区对应的Tree对象
When you run git add ., Git creates a tree object that maps out the entire directory structure of your staging area, linking each file to its blob object. Finding this tree lets you restore everything in one go:
First, scan through the lost objects to find any tree-type objects:
for obj in .git/lost-found/other/*; do if git cat-file -t "$obj" | grep -q tree; then echo "$(basename "$obj") is a tree object" fi doneFor each tree SHA1 you find, inspect its contents to confirm it's the staging state you want:
git ls-tree <tree-sha1>This will list all files and directories in the tree—match it against what you remember staging.
Once you've found the correct tree, restore it to your staging area and working directory:
# Load the tree into your staging area git read-tree <tree-sha1> # Sync the staging area to your working directory git checkout-index -aAfter running these two commands, your project should be back to exactly how it was right after you ran
git add ..
备用方案:逐个恢复Blob对象
If for some reason you can't find the right tree object (unlikely, but possible), you can restore individual blob objects:
- Check the content of a blob to identify which file it is:
git cat-file -p <blob-sha1> - Once you know the file's original path, export the blob to that path:
Note: Blob objects don't store filenames, so this method is tedious for 34k files—stick to the tree object method if you can.git cat-file -p <blob-sha1> > path/to/your/file.ext
Critical Notes
- Don't run
git gc—this will delete unreachable objects permanently, making recovery impossible. - Once you've restored everything, immediately run
git committo save the state, so you don't risk losing it again. - Going forward, use
git stashinstead ofgit reset --hardif you need to temporarily clear your working/staging area—it's safer and lets you retrieve your changes later.
内容的提问来源于stack exchange,提问作者Daarwin

