git rm -r删除项目之后,怎么找回


问题描述

今天手残, 误将 git项目删除了. 整个项目目录都清空了.

$ git rm -r .                                                           128 ↵
rm '.babelrc'
rm '.editorconfig'
 ...

解决方法

单个文件查看 ^1

$ git fsck --lost-found --unreachable
检查对象目录中: 100% (256/256), 完成.
unreachable blob 5bf9ea6d78097a6940152c4b9fa2ac76b9bf5424
unreachable blob 8c303a5578be9b49cfb9d13856615767e619dd34
unreachable blob 97c2c84832bf147b5159d184954662aca1b9ea4f
unreachable blob bbb253763a28425858ee81b33ac26e4ce4164159
unreachable blob c3930d9005d2445ad0d213138b8b01885078336a
unreachable blob fca283f562ff8875c8d3496f991b5619ac68fb7d

$ git cat-file -p 5bf9ea6
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: Hello
    }
  ]
})

整个项目恢复 ^2

  1. git log 找到离没删文件前最近的commit id

  2. 通过git reset 恢复, git reset --hard "commit id"

$ git log

$ git reset --hard "9225a2ab312f49cfe7be8ba16e9ed3aa9cf54c2a"
HEAD 现在位于 9225a2a 初次提交

注意: 如果有未提交修改, 则可以使用 git stashgit stash pop ^3

$ git stash
$ git reset --hard HEAD
$ git stash pop

参考文档


Author: Itaken
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Itaken !
  TOC目录