How to undo git rm -rf dirname without a first com

2019-06-15 23:42发布

问题:

I did:

git init
git add .
git rm -rf dirname

Looking at other answsers, git reset --hard HEAD, git checkout -f and git reflog did not work, apparently because there is no HEAD to go back to, nor a commit to get the files back from.

Is there a way to get the files back?

回答1:

There is no way.

Usually, git rm checks the files have already been committed before deleting them, so you don't lose any of your work. However, using -f overrides this check.

In short:

  • Don't use -f.
  • Don't touch anything you haven't committed.


回答2:

Warning: Running git prune without the -n option (1) will erase your unreachable data.

There may be a way, using git prune and git cat-file.

Running git prune -n will list which objects would be removed by pruning:

$ git prune -n
9cc84ea9b4d95453215d0c26489d6a78694e0bc6 blob
c315143703752ef4d11ca7d93f2c324872b2ebff blob

Each line corresponds to a deleted file.

Now, using git cat-file, we are able to restore the contents of the removed file to a new file:

git cat-file -p 9cc84ea9b4d95453215d0c26489d6a78694e0bc6 > restored-filename.whatever

(1) From the git prune docs:

NAME
git-prune - Prune all unreachable objects from the object database

OPTIONS
-n
--dry-run
Do not remove anything; just report what it would remove.



回答3:

Nope, as far as I know. I believe that git unlinks the files, just like doing rm -rf does. It doesn't matter to it whether it knows about the files or not, it will gladly nuke the directory. Really, your only recourse is to try to use a file recovery tool as if you had done rm -rf



回答4:

git reset --hard helped while deletion was not commited yet and, generally speaking, deletion was interrupted by Ctrl+Z



回答5:

If git is not tracking the dirname directory, it will not allow you to delete the directory with git rm -rf as it does not know about it. You will ( would have) get an error like

fatal: pathspec 'dirname' did not match any files

Only way you could have deleted is if you had done a git add . or git add dirname after the git init. If that is the case, your files are gone and you cannot get them back as it was never committed and git doesn't track it. It is as good as doing a rm -rf on a normal folder ( and can't recover unless you have backups)