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.

This question is tagged with git git-checkout

~ Asked on 2012-03-06 20:33:42

The Best Answer is


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.

~ Answered on 2012-03-06 20:46:25


Both questions are answered in git status.

To unstage adding a new file use git rm --cached filename.ext

# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#   new file:   test

To unstage deleting a file use git reset HEAD filename.ext

# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   deleted:    test

In the other hand, git checkout -- never unstage, it just discards non-staged changes.

~ Answered on 2012-03-06 20:37:34

Most Viewed Questions: