git rm Command
git rm
Command
The git rm
command is used to remove files from both the working directory and the staging area (index) in a Git repository. This effectively deletes the files and stages the removal for the next commit.
What Does git rm
Do?
When you run git rm
, Git performs the following actions:
- Removes Files from the Working Directory: Deletes the specified files from your working directory.
- Stages the Deletion: Stages the removal of the files so that the deletion is included in the next commit.
Basic Syntax
git rm <file>
<file>
: The path to the file or files you want to remove.
Examples
Remove a Single File
To remove a single file from the repository and the working directory:
git rm filename.txt
This command removes filename.txt
from both your working directory and the staging area.
Remove Multiple Files
To remove multiple files at once:
git rm file1.txt file2.txt
This command stages the removal of both file1.txt
and file2.txt
and deletes them from the working directory.
Remove a File from the Staging Area Only
If you want to unstage a file but keep it in the working directory (i.e., remove it from the staging area only):
git reset HEAD <file>
This will unstage the file but not delete it from the working directory.
Remove a File from the Working Directory Only
If you want to keep a file in the repository but remove it from the working directory, use:
git rm --cached <file>
--cached
: Removes the file from the staging area but keeps it in the working directory.
Example:
git rm --cached example.txt
This removes example.txt
from the index (staging area) but leaves the file in your working directory. The file will no longer be tracked by Git after the commit.
Remove Files Using Wildcards
To remove files that match a pattern:
git rm '*.log'
This command removes all files with the .log
extension from the working directory and staging area.
After Using git rm
After running git rm
, you should commit the changes to finalize the removal of files from the repository:
git commit -m "Remove unnecessary files"
This creates a commit that records the deletion of the files.
Summary
Purpose:
git rm
removes files from both the working directory and the staging area, staging the removal for the next commit.Basic Syntax:
git rm <file>
Options:
--cached
: Removes the file from the staging area only, leaving it in the working directory.-r
: Recursively removes directories and their contents.
Usage: Use
git rm
to delete files from your project and prepare their removal for the next commit. If you only want to remove files from the staging area or working directory, usegit reset
orgit rm --cached
.
The git rm
command is useful for managing files in your repository, ensuring that unwanted files are properly removed and tracked changes are accurately reflected in your commits.