Removing Already Commited gitignore Files
Already committed files to your git repository that you now realized should not be part of the project? This is a common issue as projects grow from concept to ongoing development. In some cases it is nothing more than a “janitorial” concern. In other cases, such as including a node_modules directory for a node based project, it can lead to larger repositories that slow down the setup and tear down phases of a development cycle.
The biggest issue comes into play if a developer happens to include private keys or passwords in a file that got pushed to a public repository; In this case removing the file is a must. The steps below will help start the mitigation process to ensure that doesn’t happen on future commits.
Thankfully there is an easy way to remove the files and stop them from being committed on future updates.
First – update your .gitignore file and ensure the file you want to skip is on the list. If it is a single file use the full filename. The file name needs to be fully qualified as a relative path based on where your .gitignore file lives.
The example below assumes the file resides in the same directory as the .gitignore file. The file name is the same as what you’d enter in the .gitignore file.
Then update the git cache and index for that file.
git rm --cached notthisfile.txt
git update-index --skip-worktree notthisfile.txt
Removing a file in a subdirectory
In this example you’d add the mysubdir/notthisfile.txt to the .gitignore file as well.
git rm --cached mysubdir/notthisfile.txt
git update-index --skip-worktree mysubdir/notthisfile.txt
Removing Already Commited gitignore Directories
This example shows how to remove an entire build directory using git version 2.35+ CLI commands.
git rm -r --cached build/
git update-index --skip-worktree build/
git Documentation
Looking for more git commands to manage your repositories? Go directly to the official git SCM guide or follow my other git tips & tricks posts.
Have more git tips and tricks? Share them in the comments.
post image: https://pixabay.com/photos/bottle-of-wine-came-bottles-2570215/