How to remove files in git
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.
Syntax
We can use the rm command in git as follows:
git rm options filename
filename: The name of the file that we remove.
Options
[-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 with0status.[-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.
Codes
Code 1
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"
Explanation
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.
Code 2
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"
Explanation
The code snippet above deletes the file file1.txt1 from the repository without deleting the file from the local file system.
Code 3
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"
Explanation
The code snippet above explicitly deletes the file file1.txt1 from both the repository and the local file system.
Free Resources