To remove a file from a Git repository without deleting it from your local filesystem, use the git rm --cached command. This untracks the file while keeping it on your machine. Here’s how:
Step-by-Step Guide
- Remove the file from Git tracking (but keep it locally):
git rm --cached <file-path>
Example:
git rm --cached config/database.yml
- Commit the change to update the repository:
git commit -m "Remove <file> from Git tracking"
- Push to the remote repository (e.g., GitHub, GitLab):
git push origin <branch-name>
- Add the file to
.gitignore(optional, to prevent future tracking):
echo "<file-path>" >> .gitignore
git add .gitignore
git commit -m "Add <file> to .gitignore"
git push origin <branch-name>
Example Workflow
# Remove a file from Git (keep it locally)
git rm --cached secrets.env
# Commit the removal
git commit -m "Remove secrets.env from tracking"
# Push to remote
git push origin main
# Optional: Add to .gitignore to block future tracking
echo "secrets.env" >> .gitignore
git add .gitignore
git commit -m "Ignore secrets.env"
git push origin main
Key Notes
- What
--cacheddoes: Removes the file from Git’s index (staging area) but leaves the file in your working directory. - File History: The file will still exist in previous commits. To purge it entirely from Git history, use
git filter-repoorBFG Repo-Cleaner. - Directories: Use
-rto recursively remove a directory:
git rm -r --cached logs/
Common Scenarios
| Scenario | Command |
|---|---|
| Remove a single file | git rm --cached file.txt |
| Remove a directory | git rm -r --cached my_directory/ |
| Remove all files in a directory (but keep the directory) | git rm -r --cached my_directory/* |
Why Avoid git rm Without --cached?
git rm <file>deletes the file from both Git and your local filesystem.git rm --cached <file>only untracks it, leaving the file on your machine.
This method is ideal for removing sensitive files (e.g., .env, credentials) or large files accidentally committed to Git.