0

I accidentally did a

git rm filename.txt -f

I removed all my files thinking it would only remove them from the commit, now need to recover them. Is there a way or are they lost for good?

mazucci
  • 3
  • 3
  • Did you `git add filename.txt` before? If so, you may be able to recover the file from Git's object store. – j6t May 10 '21 at 08:28
  • Try `git reset --hard` instead. – matt May 10 '21 at 08:40
  • Assuming you never made any commits, you can only get the data back *from Git* if you ran `git add` on the various files. You will lose the file's *names*. If you did not even run `git add`, try some non-Git solution, such as editor backups, macOS Time Machine, and so on. – torek May 10 '21 at 09:05

2 Answers2

0

The title of your question seems to indicate no commit was done on your repo.

In that case :

  • unfortunately, if some changes on filename.txt weren't staged (e.g: weren't present in the last git add filename.txt that your ran), git doesn't have a copy of that file, you would have to look at other tools to get that file back from disk (several IDEs keep a local history of your files, or you can run disk recovery tools)
  • the version that was staged (when you last ran git add filename.txt), however, is still present somewhere in git's database

See for example this answer for one possible way to get back some data from git's storage :

#!/bin/sh

git fsck --no-reflogs --unreachable |\
    grep blob |\
    cut -d' ' -f3 |\
    sed -e 's|^\(..\)\(.*\)|.git/objects/\1/\2|' |\
    xargs ls -l -t 2> /dev/null

This should give you a list of hashes, and one of these hashes should be the content of your file. The list will be sorted in "most recent first" oerder, so with some luck your last file will be listed among the first ones.

You can run git show {hash} to view the content of the file behind a hash, and git show {hash} > back-from-the-dead.txt to restore it to a file on disk.

LeGEC
  • 46,477
  • 5
  • 57
  • 104
-1

Try

git reset head ~

If you staged your commit you can recover it, otherwise it's probably dead forever.

Robyn
  • 161
  • 1
  • 8
  • I get the following error fatal: ambiguous argument 'head': unknown revision or path not in the working tree. – mazucci May 10 '21 at 08:33
  • Try `git reset --hard` instead. But if you have never committed your files, that won’t work and the files can never be recovered. – matt May 10 '21 at 08:41
  • Seems since I didn't commit I can't recover them, thanks anyway. – mazucci May 10 '21 at 08:50
  • Always spell `HEAD` in all uppercase (or, if you don't want to bother, use `@` for short). The lowercase version sometimes works, and sometimes doesn't. In this particular case—when there are no commits yet—neither one works though.... – torek May 10 '21 at 09:04