Search code examples
gitgit-commit

How do I restore a file that is currently git committed


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.


Solution

  • 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.