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.
1 Answer
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
.
-
1please rather recommend
reset --keep
which does not touch uncommitted changes– xerufCommented Jul 11, 2023 at 5:47 -
After 5 years, I think I have better advice. Thanks for bringing this up . Commented Jul 11, 2023 at 6:40
-
I recommend quoting the pigtail while we are at it, might be erroneously interpreted by some shells– xerufCommented Jul 11, 2023 at 8:28
git checkout <commit> -- path/to/file
? Thecheckout
command can do a number of things..git status
?git checkout HEAD -- file1 file2 etc
as I say in the response I made a few minutes ago.