Исправлено: Gitignore не работает
GitHub стал ведущим пионером в области совместной работы над кодом и совместного использования репозиториев. GitHub — это в первую очередь программное обеспечение для контроля версий, которое позволяет пользователям управлять распределенным контролем версий и SCM (управление исходным кодом). Эту платформу используют крупные предприятия и компании по всему миру.

У подобных платформ есть свои технические особенности и проблемы. Одна конкретная проблема, с которой столкнулись кодеры, заключалась в том, что .gitignore не работал в GitHub. Платформа либо игнорировала .gitignore, либо работала частично. Интересно отметить, что проблема может немного отличаться в каждом случае, поскольку каждый случай представляет собой совершенно другой сценарий. Однако перечисленные нами решения будут содержать исправления, которые будут работать повсеместно.
Что такое .gitignore?
Git (или GitHub) видит каждый файл в вашем рабочем каталоге. Он характеризует каждый файл как один из трех:
- Отслеживается: эти файлы либо зафиксированы, либо ранее помещены в историю.
- Не отслеживаемые: это файлы, которые ранее не были подготовлены или зафиксированы.
- Игнорируется: это файлы, которые сам пользователь сказал Git полностью игнорировать.
Эти игнорируемые файлы могут варьироваться от сценария к сценарию и в основном представляют собой файлы, созданные компьютером или артефакты сборки. Это обычная практика; вы можете игнорировать различные другие файлы в соответствии с вашими потребностями. Вот некоторые примеры этих файлов:
- Скомпилированный код: эти файлы обычно имеют расширение .class, .pyc, .ccp и т. Д.
- Скрытые системные файлы: это файлы, которые используются системой для ее операций, но скрыты от обычного просмотра, например DS_Store или Thumbs.db и т. Д.
- Каталоги вывода сборки: в основном это каталоги / bin, / out и т. Д.
- Кеши зависимостей: эти файлы могут быть содержимым модулей / node или / packages.
- Файлы конфигурации IDE: это файлы конфигурации, которые в основном создаются или управляются вашим программным обеспечением IDE.
- Файлы, создаваемые во время выполнения: есть некоторые программы, которые создают файлы во время выполнения. Если любой из этих кодов запущен, некоторые файлы могут быть созданы во время выполнения в вашей рабочей папке, и вы можете проигнорировать их в Git.
Любой файл, который вы хотите игнорировать, отслеживается в специальном файле с именем .gitignore, который в основном проверяется в корне вашего рабочего репозитория. Согласно официальной документации GitHub по этому вопросу, конкретной команды gitignore не существует. Вместо этого вам нужно вручную отредактировать файл, который вы хотите игнорировать. Файл .gitignore содержит шаблоны, которые сопоставляются с именами файлов в вашем рабочем репозитории, и они используются, чтобы помочь определить, следует ли игнорировать конкретный файл или нет.
Что заставляет .gitignore не работать?
Функция .gitignore может работать отлично, но вы могли неправильно ее настроить. Во всех наших опросах мы приходили к выводу, что модуль действительно работает. Причина, по которой кодеры не могут использовать эту функцию, в основном потому, что они неправильно настроили файл или есть некоторые условия, которые не выполняются в базовом коде.
Вот несколько решений, которые могут сработать для вас. Каждое решение может быть неприменимо в вашем случае, поэтому убедитесь, что вы переключились на следующее, если начальные условия не выполняются.
Решение 1.Проверка файла .gitignore
Возник интересный случай, когда мы увидели, что файл .gitignore был создан в неправильном формате. Эта конкретная проблема возникла, когда пользователи создавали файл с помощью приложения по умолчанию — Блокнота в ОС Windows. Оказывается, Блокнот записывает файл в формате Unicode, а не в формате ANSI. В этом решении мы сохраним изменения Блокнота в правильном формате .gitignore и посмотрим, решит ли это проблему.
Примечание. Вам необходимо удалить расширение .txt из файла при создании нового файла с помощью Блокнота.
- После написания кода или изменений в новом текстовом документе в Блокноте щелкните Файл и выберите Сохранить как .
- Теперь перед Encoding выберите ANSI . Теперь удалите расширение файла .txt и сохраните файл с именем .gitignore . Выберите правильный каталог и сохраните.
- Теперь перейдите в каталог и проверьте, создан ли правильный файл. Теперь проверьте это еще раз с помощью Git и посмотрите, работает ли функция игнорирования должным образом.
Разработчикам следует воздерживаться от использования блокнота по умолчанию в Windows. Вместо этого вам следует использовать настоящий «программистский» блокнот. Некоторые примеры включают Notepad ++ и т. Д. В них у вас не будет таких проблем.
Примечание. Если ваш файл уже сохранен в формате UNICODE, вам следует правильно сохранить содержимое в формате ANSI, если вы хотите, чтобы ваш файл правильно определялся Git.
Решение 2. Проверка файла, который вы пытаетесь игнорировать
Еще одно условие, при котором работает .gitignore, — это то, что ваш файл еще не должен быть частью репозитория . Это очень важный аспект, так как если это правда, файл не будет проигнорирован, поскольку он уже добавлен в репозиторий. Git не может игнорировать это, даже если вы поместите его имя или правило в файл .gitignore. По сути, Git игнорирует только неотслеживаемые файлы .
Вы должны посмотреть на свою структуру (репозиторий) и убедиться, что файл, который вы пытаетесь игнорировать, не добавлен в репозиторий. Если это так, вам придется удалить файл из репозитория и после фиксации последних изменений добавить его имя в .gitignore (вы также можете скопировать содержимое файла и после его удаления реплицировать его с другим именем) .
Решение 3. Повторное добавление файлов в репозиторий
Если вы уже добавили правила в .gitignore, но файлы, которые вы хотите игнорировать, уже добавлены, мы можем повторно добавить файлы. Добавление означает, что мы удалим все из индекса Git, а затем снова добавим все обратно в ваш репозиторий. Когда мы снова добавляем файлы с нуля, будут учитываться правила, которые вы добавили в .gitignore, и будут добавлены только правильные файлы.
Примечание. Перед выполнением этого решения следует также сделать резервную копию кода в другом месте. Всегда хорошо иметь резервную копию на всякий случай.
- Выполните следующую команду. Это приведет к деактивации и удалению путей к вашим файлам из индекса git рекурсивным образом.
- После того, как это будет выполнено, вы должны выполнить следующую команду. Это вернет все ваши файлы, и, поскольку .gitignore будет иметь правила, будут обновлены только правильные файлы.
- Теперь мы зафиксируем все ваши файлы обратно в индекс, используя приведенный ниже код:
Теперь проверьте свои файлы и посмотрите, решена ли проблема, и вы можете снова использовать .gitignore без каких-либо проблем.
My .gitignore doesn’t work
In this post we will see how to resolve this common issue and understand why it happens.
Background
The .gitignore file is used to prevent Git to tracking certain files (namely ensure that certain files not tracked by Git remain untracked), for example test outputs, logs and build files.
The best practice is to create this file when the repository is created, however in most cases, this file is created after detecting that unwanted files are being stored
The Problem
The files/folder that already are in the repository will not just delete themselves just because you added them to the gitignore file. Remember, the .gitignore file ignores only files that are not tracked.
The Solution
To resolve the problem remove from the repository the tracked files contained in the .gitignore file. To achieve this use “git rm” to remove and untrack all the files in the repository, then use “git add” to re-add all the files (the files contained in the .gitignore file will not be added) and finally commit the changes.
gitignore not Working
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:
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.
About the author

John Otieno
My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list
Fix: Gitignore is not Working
GitHub has emerged to be a leading pioneer in the field of code collaboration and repository sharing. GitHub is primarily a version control software which allows users control of distributed version control and SCM (source code management). This platform is used by major businesses and companies all around the world.
.gitignore
Platforms like these have their technicalities and issues. One specific problem which the coders experienced was that .gitignore was not working in GitHub. The platform either ignored the .gitignore or worked partially. It is interesting to note that the problem might be a little different in each case since each case is a completely different scenario. However, the solutions which we list will contain fixes which will work universally.
What is .gitignore?
Git (or GitHub) sees every file in your working directory. It characterizes each file as one of the three:
- Tracked: These files are either committed or staged previously in history.
- Untracked: These are the files which haven’t been previously staged or committed.
- Ignored: These are the files which the user himself told Git to ignore completely.
These ignored files might vary scenario to scenario and are mostly machine generated files or build artifacts. This is the common practice; you might be ignoring various other files according to your own needs. Some examples of these files are:
- Compiled code: These files are usually with the extension .class, .pyc, .ccp etc.
- Hidden system files: These are files which are used by the system for its operations but are hidden from plain view, for example, DS_Store or Thumbs.db, etc.
- Build output directories: These are mostly of the directories of /bin, /out, etc.
- Dependency caches: These files might be the contents of /node or /packages modules.
- IDE Configuration files: These are config files which are mostly created or managed by your IDE software.
- Files generated at runtime: There are some programs which create files at run time. If either such code is run, some files might be generated at run time in your working folder and you might ignore them in Git.
Whichever file you wish to ignore is tracked in a special file named as .gitignore which is mostly checked in the root of your working repository. According to the official documentation of GitHub on the subject, there is no specific gitignore command. Instead, you have to manually edit the file which you wish to ignore. The .gitignore file contains patterns which are matched against the file names in your working repository and these are used to help determine whether a specific file should be ignored or not.
What causes .gitignore not to Work?
The .gitignore feature might be working perfectly but you might not have configured it properly. In all of our surveys, we came to the conclusion that the module was indeed working. The reason why coders are unable to use the feature is mostly because they haven’t properly configured the file or there are some conditions which are not being met in the underlying code.
Here are some solutions which might work for you. Each solution might not be applicable in your case so make sure that you switch to the next one if the initial conditions are not being met.
Solution 1: Checking .gitignore File
An interesting case came forth where we saw that the .gitignore file was created in the wrong format. This particular issue occurred when users created the file using the default application of Notepad in Windows OS. It turns out that Notepad writes the file in Unicode instead of ANSI format. In this solution, we will save the changes of Notepad in the correct format of .gitignore and see if this fixes the problem.
Note: You have to remove the extension of .txt from the file when you create a new file using the Notepad.
- After writing the code or changes in a new text document in Notepad, click on File and select Save As.
- Now in front of Encoding, select ANSI. Now remove the file extension of .txt and save the file with the name ‘.gitignore’. Select the correct directory and save.
- Now navigate to the directory and check if the correct file is created. Now test it again with Git and see if the Ignore feature is working as expected.
Developers should abstain from using the default Notepad in Windows. Instead, you should use proper ‘programmers’ notepad. Some examples include Notepad++ etc. In those, you will not have issues like these.
Note: If your file is already saved in UNICODE format, you should save the contents in ANSI format properly if you want your file to be detected properly by Git.
Solution 2: Checking the File you are trying to Ignore
Another condition on which .gitignore works is that your file should not be part of the repository yet. This is a very essential aspect as if this is true, the file will not be ignored as it is already added to the repository. Git cannot ignore that even if you place its name or rule in the .gitignore file. So in essence, Git only ignores untracked files.
You should look at your structure (repository) and make sure that the file which you are currently trying to ignore is not added to the repository. If it is, you would have to remove the file from the repository and after the latest changes are committed, add its name to .gitignore (you can also copy the contents of the file and after deleting it, replicate it with a different name).
Solution 3: Re-adding Files to Repository
If you have already added rules into .gitignore but the files that you want to ignore are already added, we can re-add the files. Adding means that we will remove everything from Git’s index and then add everything back into your repository again. When we add files again from scratch, the rules will be kept in mind which you have added in .gitignore and only the correct files are added.
Note: You should back up your code somewhere else as well before performing this solution. It is always good to have a backup just in case.
- Execute the following command. This will unstage and remove the paths to your files from the git index in a recursive manner.
- After this is executed, you should execute the following command. This will add all of your files back and since .gitignore will have the rules, only the correct files will be updated.
- Now we will commit all your files back into the index using the code below:
Now inspect your files and see if the issue is resolved and you can use .gitignore again without any issues.