One such feature is the gitignore file. The gitignore files allow you to specify a list of files and directories within a given repository. The files in the gitignore files are then untracked and excluded from the repository.
In some cases, you may encounter an instance where the files in the gitignore file are still included in the repository. This can lead to dangerous behaviors such as exposing sensitive information.
Let us discuss how to fix the gitignore file.
Causes of gitignore not working
There are two primary reasons why the gitignore is not working:
Fix 1- Adding file to gitignore after commit.
Adding a file to the gitignore file will not work if the file is already committed or a part of the repository.
This is because git is already tracking the file while gitignore works for untracked files.
You can remove it from the git index using the git rm command if the file you wish to ignore is part of the repository.
Open the terminal and run the command below in your repository’s directory:
The command above will remove all the files from the git index.
Next, add all the files into the repository, ignoring your target file or directory.
You can now commit your files back into the repo.
Fix 2 – Check .gitignore file Encoding
Although this is not a very common scenario, your gitignore file may not work if you use an incorrect encoding.
A .gitignore file should be in UTF-8 encoding, which covers ASCII characters.
To solve this, open your Linux terminal and run the command:
The above command should create an empty gitignore file. Next, open the file with your favorite text editor and add your gitignore entries.
On Windows, create a new file in your text editor. Save the file as .gitignore as shown:
NOTE: Ensure the save as type is set to All Files.
Fix 3 – Incorrect Filename or Path
You may add the incorrect entry to your gitignore file in some cases. This will lead to git being unable to identify the file or path you wish to ignore.
Hence, ensure that you add the full filename, directory, or extension to your gitignore file.
You can check the docs to learn how the gitignore file works.
However, GitHub has a great list of the standard gitignore templates, as shown in the resource below:
https://github.com/github/gitignore
You can check your target gitignore template and add it to your repository.
Closing
In this article, we discussed how to fix your gitignore file not working.