Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a "git rm -r -f <directory>" command be reverted?

Tags:

git

git-rm

I was setting up my first git repository and did the following,

git init

follow by some git-config stuff to setup the remote server. I then did

git add directory
git status

Whoops, I added some files which I did not want. Okay, so I should git rm to remove the directory from the commit list and start again

git rm directory

At this point I should have read the console message and documentation properly....but didn't. So I ran

git rm directory -r -f

Huh? Where did my directory go? Ah, okay, git has removed it so it is "not there" any more. So lets try,

git status
git reset --hard

After no success, some error messages and a bunch of web searches, I realised my faux pas. I should have used

git rm -r --cached directory

which would have removed it from the commit list, but not from my file system. Whoops. Fortunately nothing serious lost.

It seems like there should be a way to recover from this, but most of my searches end up pointing to the "--cached" option...and it is a bit late for that. There are no commits, so I can't just revert/pull the files (there was only a local copy).

Is it possible to get those files back?

like image 354
Duncan Drennan Avatar asked Jan 31 '12 11:01

Duncan Drennan


2 Answers

There are no commits, so I can't just revert/pull the files (there was only a local copy)

and

Is it possible to get those files back?

The answer is no.

There are no commits, hence you are not using source control.

The files never entered the object database. In general, you can never get uncomitted stuff back in git. You can most often get previously committed stuff back.

Rule of thumb: commit often

Edit

See also

  • my own answer here https://stackoverflow.com/a/6780036/85371 (look for other sources of backup) and
  • someone else's answer https://stackoverflow.com/a/6780036/85371 two months later.

I accidentally ran git reset --hard on my repo today too while having uncommitted changes too today. To get it back, I ran git fsck --lost-found, which wrote all unreferenced blobs to <path to repo>/.git/lost-found/. Since the files were uncommitted, I found them in the other directory within the <path to repo>/.git/lost-found/. From there, I can see the uncommitted files, copy out the blobs, and rename them.

Note: This only works if you added the files you want to save to the index (using git add .). If the files weren't in the index, they are lost.

like image 120
sehe Avatar answered Sep 22 '22 02:09

sehe


I did exactly the same mistake, but in spite of adding files to the git index earlier, I couldn't recover them using 'git fsck --lost-found'. Luckily, I remembered the 'Local history' tracking option in my IDE so using it, without no problem I recovered all the code except of library binaries :)

like image 41
mordka Avatar answered Sep 23 '22 02:09

mordka