2

I just started using git yesterday, and today I committed a couple files, but then for some reason they disappeared. They show up when I run the command "git log -p -2" in one of the commits I previously did, but I have no idea how to restore them to where they were originally.

8
  • git checkout <commit> -- path/to/file ? The checkout command can do a number of things.. Commented Oct 16, 2018 at 20:58
  • when I do that it says "fatal: invalid reference: rev"
    – Gderu
    Commented Oct 16, 2018 at 21:00
  • Put in a valid commit/tree-ish thing, I changed it to <commit> and linked for clarity :) Commented Oct 16, 2018 at 21:00
  • What is the output of git status? Commented Oct 16, 2018 at 21:01
  • 1
    Then it hasn't been committed. use git checkout HEAD -- file1 file2 etc as I say in the response I made a few minutes ago.
    – eftshift0
    Commented Oct 16, 2018 at 21:04

1 Answer 1

3

If it Is already committed, you could get them back from the commit before the deletion was committed. Assume that commit where they we're deleted Is D. You can do this:

git restore --worktree --staged --source=D~ -- file1 file2 # keep the pigtail
git commit -m "recovering files file1 AND file2"

You could do a git commit --amend if deletion happened in the last commit.

Original answer from 2018: If you committed their deletion and you actually don't want it, you should consider resetting --hard (use with extreme care... many tears have come out of using it). If you actually haven't committed the deletion, you could just check them out of HEAD: git checkout HEAD -- file1.txt file2.txt.

3
  • 1
    please rather recommend reset --keep which does not touch uncommitted changes
    – xeruf
    Commented Jul 11, 2023 at 5:47
  • After 5 years, I think I have better advice. Thanks for bringing this up .
    – eftshift0
    Commented Jul 11, 2023 at 6:40
  • I recommend quoting the pigtail while we are at it, might be erroneously interpreted by some shells
    – xeruf
    Commented Jul 11, 2023 at 8:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.