The command git rm is, naturally, the converse of git add. It removes a file from both the repository and the working directory. However, because removing a file tends to be more problematic (if something goes wrong) than adding a file, Git treats the removal of a file with a bit more care.
Git will remove a file only from the index or from the index and working directory simultaneously. Git will not remove a file from just the working directory; the regular rm command may be used for that purpose.
Removing a file from your directory and the index does not remove the file’s history from the repository. Any versions of the file that are part of history already committed in the repository remain in the object store and retain that history.
Continuing the example, let’s introduce an “accidental” additional file that shouldn’t be staged and see how to remove it:
echo "Random stuff" > oops# Can't "git rm" files Git considers "other" # This should be just "rm oops" $
git rm oopsfatal: pathspec 'oops' did not match any files
Since git rm is also an operation on the index, the command won’t work on a file that hasn’t been previously added to the repository or index; Git must first be aware of a file. So let’s accidentally stage the oops file:
# Accidentally stage "oops" file $
git add oops$
git status# On branch master # # Initial commit # # Changes to be committed: # (use "git rm --cached <file>..." to unstage) # # new file: .gitignore # new file: data # new file: oops #