How to remove a file from a Git repository without deleting it from the local filesystem?

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

  1. Remove the file from Git tracking (but keep it locally):
   git rm --cached <file-path>

Example:

   git rm --cached config/database.yml
  1. Commit the change to update the repository:
   git commit -m "Remove <file> from Git tracking"
  1. Push to the remote repository (e.g., GitHub, GitLab):
   git push origin <branch-name>
  1. 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 --cached does: 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-repo or BFG Repo-Cleaner.
  • Directories: Use -r to recursively remove a directory:
  git rm -r --cached logs/

Common Scenarios

ScenarioCommand
Remove a single filegit rm --cached file.txt
Remove a directorygit 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.

Leave a Reply

Your email address will not be published. Required fields are marked *