trouselife
trouselife

Reputation: 969

How do i restore my git repository after using git -r rm

I was playing round with my repository and after modifying some files I used:

git add .

the output of this was:

 Changes to be commited:
      new file:   path/to/file.txt
      modified:   path/to/file2.txt

 Changes not staged for commit:
      deleted:     path/to/file/file3.txt

so I used:

 git commit -m 'add and modify file and file2'

which gave the output:

 2 files changed, x insertions, x deletions

so I did git status which gave the output:

 Changes not staged for commit:
      (use "git add/rm <file>..." to update what will be committed)
      (use "git checkout -- <file>..." to discard changes in working directory

           deleted:
    no changes added to commit (use "git add" and or "git commit -a")

so at this point i did:

git rm -r . 

as i thought this would remove all of the 'deleted' files However this removed everything in my repository

I then did:

git reset HEAD .

after which I did git log and found the commit code for the commit I did originally in this post. This just reverted me to previous to that commit.

What I want/need is to get all the files back after the first commit 'add and modify file and file2'

Is this possible from here? I dont want to play with it anymore as I dont want to mess it up further! Thanks

Upvotes: 3

Views: 104

Answers (2)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59973

tl;dr

You were on the right track using git reset HEAD to restore your files. As long as you didn't commit the deleted files, you can simply add the --hard option to also restore the files in your working directory:

git reset --hard HEAD

The Three Modes of git reset

The git reset command is able to modify three things in your repository:

  • The HEAD reference
  • The Index
  • The Working Directory

What is going to be modified depends on the mode of operation you choose:

  • --soft modifies just the HEAD reference
  • --mixed modifies the HEAD reference and the Index
  • --hard modifies the HEAD reference, the Index and the Working Directory

If you invoke git reset without specifying one of these three arguments, the default is going to be --mixed. This means that Git is going to move the HEAD reference and update the Index but will leave your Working Directory intact.

In your case, you want to restore the files in the Working Directory as they were in your latest commit (referenced by HEAD) so you need to pass the --hard option:

git reset --hard HEAD

You can read more about how git reset works in the excellent blog post Reset Demystified.

Upvotes: 1

Ankit Bhatnagar
Ankit Bhatnagar

Reputation: 755

From git logs, check which is the correct commit id you want to roll into (check time or number of commits to verify):

Then use:

git reset --hard <tag/branch/commit id>

Upvotes: 1

Related Questions