Home > Blockchain >  Delete again a file via a previous commit that deleted that file in the first place
Delete again a file via a previous commit that deleted that file in the first place

Time:05-10

Scenario:

  • delete file.txt file, commitA and push
  • restore file.txt via git checkout commitA~1 file.txt , commitB and push

I want to delete the file again by invoking commitA by running the following checkout command:

git checkout commitA --file.txt

but I get

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

Is there a way to re-delete the file? I could just delete the file add it and commit but I am wondering if I can keep the history clean by reusing an older commit?!

Edit: I removed the Source from the file path to avoid confusions

CodePudding user response:

I want to [use git checkout to] delete the file again by invoking [the commit in which I deleted it] ...

You cannot do that. This form of git checkout (or git restore for that matter) can only add or replace the file, not remove it.

If you know that the file was removed in some specific commit and would like to remove it again, use git rm (or git rm --cached if the idea includes avoiding modifying the working tree).

If you don't know whether the file existed or not, and simply want to put it back into the same state—that is, restore it to the way it was if it existed, or remove it entirely if it did not exist, you will need an if/then test: "Did file F exist in commit C? If yes, use git checkout / git restore; if no, use git rm". To test whether it existed, consider using git ls-tree (useful if you want to check many paths) or git rev-parse (useful if you want to check a single path). You could even use the error from git checkout as an indicator that the file did not exist, although that seems a bit clumsy and perhaps error-prone.

CodePudding user response:

because your command is wrong it should go like this git restore --Source HEAD~1 file.txt note that your HEAD will be detached

and if what you want to correct is on-stage use this git restore --staged file.txt to unstage it.

  • Related