How to undo git rm -rf dirname without a first commit?
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
(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.
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.