The title says it all. There are many cases where you might be troubleshooting the .gitignore file because it is not working as expected. Here we’ll discuss two scenarios with its possible solutions.
What is the Gitignore File
The gitignore file is probably one of the most important files for you to understand whenever you use Git. This file should be named and saved explicitly as
.gitignore. On this plain text file, you would then add the paths of files or directories you want Git to not track. So whatever it is added here Git will basically ignore and not add to its tracking tree.
Here’s an example of a gitignore file contents:
On this file we basically are telling Git to ignore our
.env file which often contains API keys and the node_module folder that contains all installed NPM packages.
Scenario A: Adding a File to Gitignore after Committing it
We could complain why gitignore is not working after we mistakenly committed a file that was supposed to be ignored. So we add it to gitignore after that fact and complain that Git is still tracking it.
Well the reason for this is that we need to add files/folders before committing them. Git is already tracking them, so to untrack them again, we will need to do the following command:
git rm -rf --cached <path>
The first part git rm removes the
--cached specifies it is removed from the index but stays in the local directory.
r is recursive removal if given a directory path and
f forces it. If you are working with just file and still wanna keep it on your local do:
git rm --cached <file>
So with this you are indicating Git that you don’t want to track the file/folder provided anymore. Now try again and your gitignore will work as it should. Just remember that the file/folder must be specified for gitignore to work!
Scenario B: Gitignore Created Before Commit and Still Not Tracking File
If this is the case, then the solution might be simple and you might actually have to check that you are providing the correct path and file name.
Also check that you don’t have any trailing space at the beginning nor end of file/folder declaration.
We discussed a few scenarios and possibilities of solutions for various cases when gitignore wasn’t working as expected. The main takeaway is that you must understand where the files/directories are located so you can add the correct path.
You must also be aware that as soon as you create a file that needs to be ignored just add the file to gitignore right away. If you happen to have committed it by mistake, luckily we have the
git rm -rf --cached <path> that will take it out from the Git workflow so you can add it to gitignore and will work as it should.
Final Note: There might be other cases that Git reset might be useful, I wrote an article regarding Git Reset that will be useful in these cases. So Git reset will be like undoing, going back in time, so in some cases that is what you want.