We use the git rm
command in git to remove files from a git repository. If the user does not specify anything, the git rm
command also removes the file from the file system.
We can use the rm
command in git as follows:
git rm options filename
filename
: The name of the file that we remove.[-f]
: Forced remove. This overrides the up-to-date check.[--cached]
: Removes file from the staging area. The copy of the file from the disk is not deleted.[-q]
: Remove the file quietly without showing any output.[--ignore-unmatch]
: If there is no file with the given name, ignore the un-match and exit with 0
status.[-n]
: Dry run. Does not perform the actual removal. This only shows what would happen.[--]
: Separates the options from the filenames.Git rm
vs rm
The git rm
command removes the file from both the git repository and the local file system. The rm
command, on the other hand, only removes the file from the file system.
Consider the code snippet below which demonstrates the use of the rm
command:
git rm file1.txtgit commit -m "file1.txt removed from current directory"
The code snippet above removes the file file1.txt
from the current directory. We use the commit
command in line 3 to save the changes of the removed file to the local repository.
Consider the code snippet below, which demonstrates the use of the rm
command with cached
option:
git rm --cached file1.txtgit commit -m "file1.txt removed from current directory"
The code snippet above deletes the file file1.txt1
from the repository without deleting the file from the local file system.
Consider the code snippet below, which demonstrates the use of the rm
command with force remove
option.
git rm -f file1.txtgit commit -m "file1.txt removed from current directory"
The code snippet above explicitly deletes the file file1.txt1
from both the repository and the local file system.
Free Resources