Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 594
lurscher Avatar asked Mar 06 '12 20:03

lurscher


People also ask

How do I Unstage deleted files?

In your case you must have used git rm to remove the file, which is equivalent to simply removing it with rm and then staging that change. If you first unstage it with git reset -- <file> you can then recover it with git checkout -- <file> .

How do I undo a deleted file in git?

Recovering Deleted Files with the Command Line Recovering a deleted file using the Git command line involves the ` git restore ` or ` git checkout `command. Whenever you modify files in Git—including creating new files, editing, or deleting existing files—the changes start as unstaged.

Is it still possible to restore deleted untracked files in git?

You can't access to previous version of untracked deleted files from git, because, of coruse, they do not exist.


2 Answers

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.

like image 56
twalberg Avatar answered Sep 17 '22 12:09

twalberg


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.

like image 21
seppo0010 Avatar answered Sep 20 '22 12:09

seppo0010