Deleting & Untracking Files
Learn about Deleting & Untracking Files
Deleting files in a Git project requires a bit more thought than just pressing Delete. You need to tell Git about the removal, and sometimes you want to stop tracking a file without deleting it from disk. This episode covers every file removal scenario.
Removing Files from Git and Disk
# Delete a file and stage the deletion in one step
git rm old-file.txt
git commit -m "Remove old-file.txt"
# Same as doing:
rm old-file.txt # Delete from disk
git add old-file.txt # Stage the deletion
Removing from Git but Keeping on Disk
This is common when you accidentally committed a file that should be ignored (like .env or node_modules):
# Stop tracking but DON'T delete the file
git rm --cached .env
git commit -m "Remove .env from tracking"
# Stop tracking an entire directory
git rm -r --cached node_modules/
git commit -m "Remove node_modules from tracking"
# The file still exists on your computer — Git just stops tracking it.
# Add it to .gitignore to prevent re-adding.
Renaming / Moving Files
# Rename a file (Git tracks this as a rename, not delete+create)
git mv old-name.js new-name.js
git commit -m "Rename old-name.js to new-name.js"
# Move a file to another directory
git mv src/utils.js lib/utils.js
git commit -m "Move utils.js to lib directory"
Discarding Changes
# Discard changes to a file (revert to last committed version)
git restore index.html
# Discard ALL changes in working directory
git restore .
# Older syntax (still works)
git checkout -- index.html
# WARNING: These commands permanently discard your changes!
# There's no undo for uncommitted changes.
Cleaning Untracked Files
# See what would be removed (dry run)
git clean -n
# Remove untracked files
git clean -f
# Remove untracked files AND directories
git clean -fd
# Remove ignored files too (nuclear option)
git clean -fdx
Common Scenarios
Accidentally Committed node_modules
echo "node_modules/" >> .gitignore
git rm -r --cached node_modules/
git commit -m "Remove node_modules, add to gitignore"
Accidentally Committed a Secret (.env)
echo ".env" >> .gitignore
git rm --cached .env
git commit -m "Remove .env from tracking"
# Important: The secret is still in Git history!
# Change the actual secret/password immediately.
What's Next
You can now manage file additions and removals confidently. In the next episode, we'll explore the project history — viewing commits, comparing changes, and understanding how Git stores time.