When working with Git, developers sometimes accidentally commit files that shouldn't be tracked, such as IDE configuration files (*.iml, *.project, *.settings) or editor metadata (.idea/*). While adding these to .gitignore prevents future commits, occasionally these files get pushed to remote repositories. This guide demonstrates how to remove such files from Git's tracking while presevring them locally.
The following approach is suitable when you need to remove files from the staging area or branch history while keeping them in your working directory.
Example scenario: Removing a configuration file named project-config.iml
- Preview which files would be removed (dry run):
git rm -r -n --cached path/to/file-or-directory
$ git rm -r -n --cached project-config.iml
rm 'src/main/project-config.iml'
The -n flag performs a dry run, showing what would be removed without actual deletion. The -r parameter enables recursive removal for directories.
- Execute the removal from staging:
git rm -r --cached path/to/file-or-directory
$ git rm -r --cached project-config.iml
rm 'src/main/project-config.iml'
- Commit the staging changes:
git commit -m "Remove project-config.iml from version control"
$ git commit -m "Remove project-config.iml from version control"
[main 2b8d91f] Remove project-config.iml from version control
1 file changed, 0 insertions(+), 120 deletions(-)
delete mode 100644 src/main/project-config.iml
- Push changes to remote repository:
git push origin main
For complete removal (both from Git and local workspace):
git rm file_path
git commit -m "Permanently remove file"
git push origin branch_name