Help, I deleted a file by accident
Bring a deleted file back from Git, whether you deleted it a minute ago or in a commit last week.
git status Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) deleted: index.html
The fix
git restore --staged --worktree index.htmlBrings the file back from your last commit, whether you deleted it with
rmor withgit rm.
index.html is an example. Replace it with your own.
git log --oneline -- index.htmlThe newest line is the commit that deleted the file. Keep the
--: the file no longer exists, so Git needs to know it is a path.git restore --source=a1b2c3d~1 index.htmlRestores the file as it was one commit before the deletion.
git add index.htmlStage it again.
git commit -m "Restore index.html"And commit it back into history.
index.html is an example. Replace it with your own.
Why this works
As long as a file was committed once, Git still has every committed version of it. If the deletion is not committed yet, restore it from your last commit. If it is, look up the commit that deleted it and take the version from just before: ~1 means one commit earlier. A file that was never committed was never in Git, so Git cannot bring it back.