Sometimes we accidentally commit and publish sensitive files, credentials or even private API keys to our repositories. Undoing this blunder can be quite frustrating if you are not familiar with git, but thankfully it’s a straightforward process.
Here are the 3 simple steps you need to untrack a file from git
- Tell Git to untrack the specific file or folder
- Tell Git to ignore the file in future commits
- Commit your changes
Tell Git to untrack the specific file or folder
Navigate to your project’s root directory in the CLI and execute git’s rm command.
For Untracking single files use:
1
git rm --cached <filename>
For Untracking multiple files, simply append the files:
1
git rm --cached <filename> <filename2> <filename3>
For Untracking an entire folder
Use the recursive flag option like below:
1
git rm -r --cached <folder>
All of the commands above tells git to untrack the specific files without deleting the files from your local disk. This is because of the –cached flag that is suffixed after the git word. Removing the –cached flag will delete the files both from git and the local copy on disk.
Again note that running the command below deletes the file from both git and your computer
1
git rm <filename>
Tell Git to ignore the file in future commits
- Create a .gitignore file if your project does not have one already.
- Update the .gitignore file to include the file/folder you want to untrack and ignore.
If your project doesn’t have a .gitignore file you can create one by executing this command in your project’s root directory:
1
touch .gitignore
Then open the gitignore file with:
1
open .gitignore
Update the content of the gitignore file to reflect the files and folders you want to ignore and save it.
A gitignore file is a file that tells Git which files or folders to ignore. Gitignore file is usually placed in the root directory of a project.
For more about gitignore - read this gitignore article
Commit your changes
You can confirm that the untracked files and folders was deleted from git by using git status command.
Once you’re sure that the files are deleted from git, stage and commit your changes.
Voila🎉 git will now stop tracking the specific files and folders in future commits.