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.
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> .
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.
You can't access to previous version of untracked deleted files from git, because, of coruse, they do not exist.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With