On This Page

How to Remove a File from Git Without Deleting It Locally

Quick Answer: To stop tracking a file in Git while keeping it on your local hard drive, run git rm --cached <file-name>. Then, add the file to your .gitignore file and commit: git commit -m "Stop tracking <file-name>".


Quick Reference Commands

GoalCommand
Stop tracking 1 file (keep local file)git rm --cached <file-name>
Stop tracking a directory (keep local folder)git rm -r --cached <folder-name>
Delete file from both Git AND local diskgit rm <file-name>
Stop tracking all .gitignored filesgit rm -r --cached . && git add .

Step-by-Step Guide

Step 1: Remove File from the Git Index

The --cached flag tells Git to delete the file from the Staging Area (the Index) while leaving your physical file in your workspace untouched:

$ git rm --cached .env

Step 2: Add the File to .gitignore

If you do not add the file to .gitignore, Git will mark it as an “untracked file” during git status and you might accidentally stage it again later:

$ echo ".env" >> .gitignore

Step 3: Commit the Change

Record the untracking change in your repository history:

$ git add .gitignore
$ git commit -m "Stop tracking .env configuration file"

How to Stop Tracking an Entire Folder

If you accidentally committed a directory like node_modules/, build/, or .idea/:

# 1. Remove the entire directory from index recursively (-r)
$ git rm -r --cached build/

# 2. Add to .gitignore
$ echo "build/" >> .gitignore

# 3. Commit
$ git add .gitignore
$ git commit -m "Remove build directory from Git tracking"

What Happens Under the Hood?

When you run git rm --cached <file>, Git deletes the entry for <file> inside the binary .git/index manifest, but does not issue an unlink() system call on your filesystem.

When you commit, the new tree object generated for the repository will no longer contain a reference to that file blob. Read /git-add and /git-commit for details on index manifest operations.