How can I ignore files that have already been committed to the repo?
Short answer
Git's .gitignore file only prevents untracked files from being staged; if a file is already tracked by Git, adding it to .gitignore has no effect on its future tracking. To stop Git from tracking a file while keeping it on disk, run git rm --cached path/to/file, which removes the file from the index without deleting it from your working directory. After running git rm --cached, add the file path to .gitignore and commit both the removal from the index and the updated .gitignore together. For entire directories, use git rm -r --cached path/to/directory/ to recursively remove all contained files from tracking. Going forward, Git will ignore future changes to that file, but all previous committed versions remain accessible in the project's history.
Git can only ignore files that are untracked - files that haven't been committed to the repository, yet. That's why, when you create a new repository, you should also create a .gitignore file with all the file patterns you want to ignore. You can use our handy .gitignore generator to speed things up.
However, of course, not everything goes perfect... and files slip through that you later would like to see ignored.
The Git Cheat Sheet
No need to remember all those commands and parameters: get our popular "Git Cheat Sheet" - for free!
Free. We email you a ZIP with our cheat sheets.
Preparing the Cleanup
Before cleaning up your repository, you should conduct two important preparations:
- Make sure your .gitignore file is up-to-date and contains all the correct patterns you want to ignore.
- Commit or stash any outstanding local changes you might have. Your working copy should be clean before you continue.
No Command Line Needed
How to Ignore Files
Our free online book explains the general process of how to ignore files in great detail.
Cleaning Ignored Files
In three steps, you can clean up your repository and make sure your ignored items are indeed ignored:
# Remove the files from the index (not the actual files in the working copy)
$ git rm -r --cached .
# Add these removals to the Staging Area...
$ git add .
# ...and commit them!
$ git commit -m "Clean up ignored files"
No Command Line Needed
Ignoring Committed Files in Tower
In case you are using the Tower Git client, the app does the heavy lifting for you: when trying to ignore a file that is already tracked in Git, Tower will ask if you want to untrack it - so that the ignore rules can do their work.
Learn More
- Check out the chapter Starting with an Unversioned Project – Command Line edition in our free online book