DEV Community

Sufiyan Yasa
Sufiyan Yasa

Posted on • Originally published at sufiyanyasa.com

Commit Mistake: How to untracked files in Git

My Reason to Git stop tracking file

There are a couple of reasons to untrack a file in your git repository.
Though my obvious reason is because of fat fingers.
Sometimes I accidentally committed a binary file with git add ..

Thus it is pretty handy to know how to untrack files in Git.
Plus it is super easy.

Tell Git to untrack file

Use git rm to Git untrack file.

git rm --cached <filename>
Enter fullscreen mode Exit fullscreen mode

And if you need untrack more that one file, simply append the files:

git rm --cached <filename>  <filename2>  <filename3>
Enter fullscreen mode Exit fullscreen mode

Both of the commands above git untrack file without deleting.
This is because of the cached option. Removing the cached option will
delete it from your disk.

git rm <filename>
Enter fullscreen mode Exit fullscreen mode

After run this command, don't forget to commit the changes. Git update on other developers
machine will automatically remove this file

Tell Git untrack folder

What about when a whole folder needs to be untracked?
Removing a whole directory is simple too with the recursive option.

git rm -r --cached <folder>
Enter fullscreen mode Exit fullscreen mode

If needed, ignore the file in the future

Optionally, once you have the file removed, you can add it to your git ignore file.
Conveniently, this file is called gitignore.

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

Why use 'git rm' to remove a file instead of 'rm'?

Technically they are both the same. git rm does 2 commands at once:

  1. Removing the file from index
  2. Staging the next commit with the removed file

rm only removes the file from disk. You will still the to stage and commit the deleted file.
git rm does that in one single step.

Top comments (0)