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?
There is another way to undo the git rm command. We can also do it by git checkout command. A checkout has the same effect and restores the latest version of a file from HEAD.
By default, the git rm command deletes files both from the Git repository as well as the filesystem. Using the --cached flag, the actual file on disk will not be deleted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With