Home How to remove and untrack committed files in git
Post
Cancel

How to remove and untrack committed files in git

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

  1. Tell Git to untrack the specific file or folder
  2. Tell Git to ignore the file in future commits
  3. 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

  1. Create a .gitignore file if your project does not have one already.
  2. 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.

This post is licensed under CC BY 4.0 by the author.