Unstage a deleted file in git

Usually, to discard changes to a file you would do:

git checkout -- <file>

What if the change I want to discard is deleting the file? The above line would give an error:

error: pathspec '<file>' did not match any file(s) known to git.

What command will restore that single file without undoing other changes?

bonus point: Also, what if the change I want to discard is adding a file? I would like to know how to unstage that change as well.

7 s
7

Assuming you’re wanting to undo the effects of git rm <file> or rm <file> followed by git add -A or something similar:

# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>

To undo git add <file>, the first line above suffices, assuming you haven’t committed yet.

Leave a Comment