How To Remove Committed Files From Git Version Control

How To Remove Committed Files From Git Version Control

Do it without getting rid of files which shouldn?t be pushed to the repository

Image for postPhoto by Yancy Min on Unsplash

Most of us have probably committed something to a repository, maybe even a public one, that we don?t want: credentials, build files, temporary files. Potential issues:

  • Published sensitive data (e.g., environment files which contain login credentials to a database or API keys)
  • Build files which change regularly without being needed
  • User-specific files (e.g., personal IDE settings)

A good example is the .idea folder which is created if you use IDEs made by JetBrains (e.g., IntelliJ IDEA). Let?s suppose someone added this folder by accident, which makes it version controlled. Anytime someone makes changes to his personal IntelliJ configuration, Git tells us we?ve changed this file. But other developers shouldn?t be forced to use the same configuration. Additionally, this makes merging/rebasing more difficult.

Hence, I want to remove this folder from version control and make sure nobody can add it to the repository anymore. However, I don?t want it to be deleted from my local machine since the folder is needed. Therefore, we can?t simply remove the files and commit this as this would also delete those files locally once pulling these changes.

Therefore, we need a way to remove committed files from version control without modifying local data. Luckily, using Git, we can easily solve this problem.

Image for post

How to remove committed files from Git version control

  1. Create a .gitignore file, if you haven?t already
  2. Edit .gitignore to match the file/folder you want to ignore
  3. Execute the following command: git rm –cached path/to/file. Git will list the files it has deleted. The –cached flag should be used if you want to keep the local copy but remove it from the repository.
  4. Verify that these files are being deleted from version control using git status
  5. Push the changes to the repository

After completing these steps, those files should be removed from version control but not removed from any local machine. Any other developer which pulls again after you pushed your changes should have no issues.

Note: it?s still possible to retrieve such data from Git history. Therefore, you need to remove it from Git history if it?s sensitive data you want to get rid of. Check out huffleHog in case you want to remove such data from your Git repository.

No Responses

Write a response