Git tracks files through an index, commonly called the “Git cache” or staging area. This index records which files are being tracked and their current state. When you update your .gitignore file to exclude files that are already tracked, Git continues tracking them because they exist in the index. Clearing the Git cache forces Git to re-evaluate which files should be tracked based on your current .gitignore rules.
This guide demonstrates how to clear the Git cache using the command-line terminal. You will learn how to remove all files from the index (useful when .gitignore changes are not being respected), remove specific files or directories, and clear cached credentials for security purposes. By the end, you will understand exactly what each command does and when to use it.
This guide assumes Git is already installed on your system. If you need to install Git first, see our installation guides for Ubuntu, Debian, Fedora, or Linux Mint.
Understanding the Git Index and Cache
Before clearing the cache, it helps to understand what you are actually clearing. Git uses several types of “caches,” and confusing them leads to unexpected results:
- The Git index (staging area): This is the primary cache most users refer to. It tracks which files are staged for the next commit and which files Git monitors for changes. Clearing this cache is necessary when you want Git to re-read your
.gitignorefile and stop tracking files that should be ignored. - The credential cache: Git can temporarily store your username and password in memory so you do not have to re-enter them for every remote operation. This is separate from the index.
- The object cache: Git stores compressed objects (commits, trees, blobs) in
.git/objects/. Thegit gccommand manages this cache, but it is rarely needed for day-to-day work.
This guide primarily covers clearing the Git index, which is the most common task when .gitignore changes are not reflected in your repository.
Clear the Entire Git Cache
Clearing the entire Git cache is the standard approach when you have updated your .gitignore file and Git is still tracking files that should now be ignored. This process removes all files from the index, then re-adds them while respecting the current .gitignore rules.
Navigate to Your Repository
First, open a terminal and navigate to your Git repository’s root directory. All subsequent commands must be run from within a Git repository:
cd ~/your-git-repository
Replace ~/your-git-repository with the actual path to your project. For example, cd ~/projects/my-website or cd /var/www/html/my-app.
Remove All Files from the Index
Next, remove all files from the Git index. This command does not delete any files from your working directory; it only removes them from Git’s tracking system:
git rm -r --cached .
The flags in this command serve specific purposes:
-r(recursive): Processes all files in all subdirectories, not just the current directory.--cached: Removes files from the index only, leaving your actual files untouched on disk..: Targets everything in the current directory and below.
After running this command, you will see output listing every file being removed from the index:
rm 'README.md' rm 'src/app.js' rm 'src/config.json' rm 'logs/debug.log' rm '.env'
This output confirms the files have been removed from tracking. Your actual files remain in place.
Verify the Current Status
Before re-adding files, check the repository status to understand what Git sees:
git status
At this point, Git shows all previously tracked files as both “deleted” (staged for removal) and “untracked” (no longer in the index):
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
deleted: .env
deleted: README.md
deleted: logs/debug.log
deleted: src/app.js
deleted: src/config.json
Untracked files:
(use "git add <file>..." to include in what will be committed)
.env
.gitignore
README.md
logs/
src/
Notice that all files appear in both sections. The “deleted” entries are staged changes (Git plans to remove them from the next commit), while the “untracked” entries show the same files now exist outside Git’s awareness.
Re-add Files Respecting .gitignore
Now re-add all files to the index. This time, Git reads your .gitignore file and excludes any matching patterns:
git add .
After this command, check the status again to see the result:
git status
If your .gitignore contains patterns like *.log and .env, those files now appear only as deleted (they will be removed from tracking) while legitimate files are re-added:
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: .gitignore
deleted: .env
deleted: logs/debug.log
This output shows exactly what will happen on the next commit: the .gitignore file will be added, and the previously tracked files matching ignore patterns (.env and logs/debug.log) will be removed from the repository.
Commit the Cache Clear
Finally, commit the changes to record this cache reset in your repository history:
git commit -m "Clear cache and apply updated .gitignore rules"
The commit message should describe what you did. A clear message helps when reviewing history later:
[main a1b2c3d] Clear cache and apply updated .gitignore rules 3 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 .gitignore delete mode 100644 .env delete mode 100644 logs/debug.log
After this commit, the files matching your .gitignore patterns are no longer tracked. They remain in your working directory but will not appear in future commits.
If you have already pushed to a remote repository, you will need to push this commit (
git push) for the changes to appear on the remote. The ignored files will be removed from the remote repository as well, so ensure this is your intended outcome.
Clear the Git Cache for Specific Files
When you only need to stop tracking a few files rather than clearing the entire cache, you can target specific files or directories. This approach is cleaner when you accidentally committed a single configuration file or secret.
Remove a Single File from Tracking
To stop tracking a single file while keeping it in your working directory, use the --cached flag without the recursive option:
git rm --cached config/secrets.json
Git confirms the removal:
rm 'config/secrets.json'
The file remains on your disk but is no longer tracked by Git. Add the file pattern to your .gitignore to prevent accidentally tracking it again:
echo "config/secrets.json" >> .gitignore
Remove a Directory from Tracking
For directories, add the -r (recursive) flag to remove the directory and all its contents from tracking:
git rm -r --cached logs/
This removes all files within the logs/ directory from the index:
rm 'logs/access.log' rm 'logs/debug.log' rm 'logs/error.log'
Add the directory to .gitignore to keep it ignored:
echo "logs/" >> .gitignore
Commit the Selective Removal
After removing specific files or directories, verify the changes and commit:
git status
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitignore
deleted: logs/access.log
deleted: logs/debug.log
deleted: logs/error.log
Then commit with a descriptive message:
git commit -m "Remove logs directory from tracking and update .gitignore"
Clear Cached Git Credentials
Git can cache your authentication credentials to avoid repeated password prompts when pushing to or pulling from remote repositories. On shared systems or when rotating credentials, clearing this cache is important for security.
Clear the In-Memory Credential Cache
If you are using Git’s built-in credential cache (enabled with git config credential.helper cache), credentials are stored temporarily in memory. To clear them immediately:
git credential-cache exit
This command terminates the credential cache daemon, removing any stored credentials from memory. The command produces no output on success. If no cache daemon is running, the command still succeeds silently.
Check Your Credential Helper Configuration
Different systems use different credential storage methods. To see which credential helper you are using:
git config --get credential.helper
Common outputs include:
cache: Credentials stored in memory for a limited time (default 15 minutes).store: Credentials stored in plain text in~/.git-credentials.managerormanager-core: Git Credential Manager (common on Windows and macOS).libsecretorgnome-keyring: Credentials stored in the system keyring (common on Linux desktops).
Clear Stored Credentials
If you are using the store helper, credentials are saved in a plain text file. To remove them:
rm ~/.git-credentials
For system keyring-based helpers like libsecret or gnome-keyring, use your desktop’s keyring manager (such as Seahorse on GNOME) to remove the stored credentials.
Disable the Credential Helper Entirely
To stop Git from caching credentials altogether, remove the credential helper configuration:
git config --global --unset credential.helper
After this, Git will prompt for your username and password on every remote operation. For most workflows, using SSH keys or a secure credential manager is preferable to disabling caching entirely.
Verify .gitignore Rules
After clearing the cache and updating .gitignore, you may want to verify that specific files are correctly ignored. Git provides a built-in tool for this purpose.
Test a File Against .gitignore
The git check-ignore command tells you whether a file matches any ignore rule and shows which rule is responsible:
git check-ignore -v logs/debug.log
The -v (verbose) flag shows the source file, line number, and pattern that matched:
.gitignore:3:*.log logs/debug.log
This output indicates that line 3 of .gitignore contains the pattern *.log, which matches logs/debug.log. If the file is not ignored, the command produces no output.
Test Multiple Files
You can test multiple files at once:
git check-ignore -v .env config/secrets.json node_modules/
Each matched file or directory appears with its corresponding rule:
.gitignore:1:.env .env .gitignore:5:config/secrets.json config/secrets.json .gitignore:8:node_modules/ node_modules/
Files that are NOT ignored produce no output. This is a quick way to debug why a file is or is not being ignored.
Troubleshooting Common Issues
Clearing the Git cache is usually straightforward, but a few common issues can cause confusion.
Files Still Appear After Cache Clear
If files still show as tracked after running the cache clear commands, you may have forgotten to commit the changes. Verify with:
git status
If you see “Changes to be committed” that include deleted files, you need to complete the commit:
git commit -m "Apply .gitignore and remove ignored files from tracking"
.gitignore Pattern Not Working
If a file is not being ignored despite being in .gitignore, check these common causes:
- The file was already tracked before being added to .gitignore: Clear the cache as described in this guide. Adding a pattern to
.gitignoreonly affects new files; already-tracked files must be explicitly removed from the index. - Pattern syntax error: Verify the pattern with
git check-ignore -v filename. Common mistakes include missing slashes for directories (logs/vslogs) or incorrect wildcard placement. - Negation rule overriding the ignore: A later rule in
.gitignorestarting with!may be un-ignoring the file. Check your entire.gitignorefor conflicting rules.
Changes Not Reflected on Remote
After clearing the cache locally and committing, you must push to update the remote repository:
git push origin main
Replace main with your branch name if different. After pushing, the ignored files will be deleted from the remote repository. Other team members will see these files removed on their next pull.
Removing files from the repository does not delete them from other developers’ working directories. The files will remain as untracked on their machines after they pull the commit. However, if those files were genuinely sensitive (like credentials), consider rotating them since they exist in the repository history.
Use a Global .gitignore for Personal Files
Developers often work with tools that create local files irrelevant to the project itself, such as editor configuration files (.vscode/, .idea/), OS-specific files (.DS_Store, Thumbs.db), or personal notes. Instead of adding these to every project’s .gitignore, you can create a global ignore file that applies to all your repositories.
First, create a global .gitignore file in your home directory:
touch ~/.gitignore_global
Add your personal ignore patterns to this file. For example:
cat <<EOF >> ~/.gitignore_global
# Editor directories
.vscode/
.idea/
*.swp
*~
# OS files
.DS_Store
Thumbs.db
# Personal notes
TODO.md
notes.txt
EOF
Then configure Git to use this file globally:
git config --global core.excludesfile ~/.gitignore_global
Verify the configuration:
git config --get core.excludesfile
/home/username/.gitignore_global
From now on, files matching these patterns will be ignored in all your repositories without polluting each project’s .gitignore with personal preferences.
Optimize and Clean Up the Object Cache
While the Git index (staging area) is what most people mean by “cache,” Git also maintains an object database that can accumulate loose objects over time. The git gc command compresses and cleans up this storage.
To run garbage collection and prune all unreachable objects immediately:
git gc --prune=now
This command:
- Compresses loose objects into pack files for more efficient storage.
- Removes objects that are no longer referenced by any branch or tag.
- Cleans up temporary files and optimizes the repository structure.
Example output:
Enumerating objects: 1543, done. Counting objects: 100% (1543/1543), done. Delta compression using up to 8 threads Compressing objects: 100% (892/892), done. Writing objects: 100% (1543/1543), done. Total 1543 (delta 651), reused 1200 (delta 500), pack-reused 0
Git runs garbage collection automatically in the background during normal operations, so manual execution is rarely necessary. Consider running it after large operations like rebasing many commits, deleting old branches, or importing from another version control system.
Clean Up Merged Branches
As projects grow, merged branches accumulate. Cleaning up these old branches keeps your repository organized and makes branch listings easier to navigate.
First, list all branches that have been merged into your current branch:
git branch --merged
feature-login feature-dashboard bugfix-header * main
The asterisk indicates your current branch. To delete all merged branches except main and master:
git branch --merged | grep -Ev "(^\*|main|master)" | xargs git branch -d
This command pipeline:
git branch --merged: Lists branches merged into the current branch.grep -Ev "(^\*|main|master)": Excludes the current branch (marked with*) and the protected branchesmainandmaster.xargs git branch -d: Passes the remaining branch names togit branch -dfor deletion.
The -d flag uses “safe” deletion, which only deletes branches that have been fully merged. Git will refuse to delete branches that contain unmerged changes. For more information on managing branches, see our guide on renaming local and remote Git branches.
Conclusion
Clearing the Git cache resolves tracking issues when your .gitignore file is not being respected for already-tracked files. The key commands are git rm -r --cached . to remove all files from the index, followed by git add . to re-add them while respecting current ignore rules, and a commit to record the change. For selective removal, target specific files or directories with git rm --cached filename. Credential caches are separate and can be cleared with git credential-cache exit or by removing stored credential files. Regular use of git check-ignore -v helps debug ignore rules, and occasional git gc runs keep the object database optimized.