Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to undo git rm -rf dirname without a first commit?

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?

like image 867
B Seven Avatar asked Mar 10 '12 05:03

B Seven


People also ask

How do I undo a rm in git?

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.

Does git rm actually delete the file?

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.


1 Answers

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.

like image 51
Anderson Vieira Avatar answered Sep 29 '22 18:09

Anderson Vieira