How to use gitignore
How to use gitignore
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
.gitignore tells git which files (or patterns) it should ignore. It’s usually used to avoid committing transient files from your working directory that aren’t useful to other collaborators, such as compilation products, temporary files IDEs create, etc.
You can find the full details here.
It’s a list of files you want git to ignore in your work directory.
The git docs will tell you all you need to know: http://git-scm.com/docs/gitignore
Also, importantly git status is one of the most frequently used command where you want git status to list out the files that have been modified.
You would want your git status list look clean from unwanted files. For instance, I changed a.cpp, b.cpp, c.cpp, d.cpp & e.cpp I want my git status to list the following:
I dont want git status to list out changed files like this with the intermediary object files & files from the build folder
There are files you don’t want Git to check in to. Git sees every file in your working copy as one of three things:
Ignored files are usually built artifacts and machine-generated files that can be derived from your repository source or should otherwise not be committed. Some common examples are:
Игнорировать изменения файлов с помощью Git
Azure DevOps Services | Azure DevOps Server 2022 | Azure DevOps Server 2020 | | Azure DevOps Server 2019 г. TFS 2018
| Visual Studio 2022 Visual Studio 2019 | | Visual Studio 2017 Visual Studio 2015
В этой статье раскрываются следующие темы:
Использование файла gitignore
Visual Studio Git
В окне изменений Git щелкните правой кнопкой мыши любой измененный файл, который вы хотите игнорировать Git, и выберите » Пропустить этот локальный элемент » или «Пропустить это расширение«. Эти параметры меню не существуют для отслеживаемых файлов.
Обозреватель Team Explorer в Visual Studio
В представлении «Изменения»Team Explorer щелкните правой кнопкой мыши любой измененный файл, который требуется пропустить Git, и выберите » Пропустить этот локальный элемент » или «Пропустить это расширение«. Эти параметры меню не существуют для отслеживаемых файлов.
Изменение файла gitignore
Ниже приведены некоторые примеры распространенных шаблонов поиска файлов:
Использование глобального файла gitignore
Использование файла исключения
Записи в exclude файле применяются только к неотслеченным файлам и не препятствуют Git сообщать об изменениях в зафиксированных файлах, которые уже отслеживаются. Для каждого репозитория существует только один exclude файл.
Так как Git не фиксирует или не отправляет exclude файл, его можно безопасно использовать, чтобы игнорировать файлы в локальной системе, не затрагивая других пользователей.
Использование индекса обновления Git для пропуска изменений
Иногда бывает удобно временно прекратить отслеживание локального файла репозитория и игнорировать изменения в файле Git. Например, может потребоваться настроить файл параметров для среды разработки без риска фиксации изменений. Для этого можно выполнить git update-index команду с флагом skip-worktree :
Использование Git rm для пропуска изменений
Игнорирование файлов и каталогов в Git (.gitignore)
Какие файлы следует игнорировать?
Игнорируемые файлы обычно представляют собой файлы для конкретной платформы или автоматически созданные файлы из систем сборки. Вот некоторые общие примеры:
.gitignore Шаблоны
.gitignore — это простой текстовый файл, в каждой строке которого содержится шаблон, который файлы или каталоги следует игнорировать.
Он использует шаблоны подстановки для сопоставления имен файлов с подстановочными знаками. Если у вас есть файлы или каталоги, содержащие шаблон подстановки, вы можете использовать одиночную обратную косую черту ( ) для экранирования символа.
Комментарии
Строки, начинающиеся с решетки ( # ), являются комментариями и игнорируются. Пустые строки можно использовать для улучшения читаемости файла и для группировки связанных строк шаблонов.
Если шаблон начинается с косой черты, он соответствует файлам и каталогам только в корне репозитория.
Если шаблон не начинается с косой черты, он соответствует файлам и каталогам в любом каталоге или подкаталоге.
Если шаблон заканчивается косой чертой, он соответствует только каталогам. Когда каталог игнорируется, все его файлы и подкаталоги также игнорируются.
Буквальные имена файлов
Самый простой шаблон — это буквальное имя файла без каких-либо специальных символов.
Шаблон | Примеры совпадений |
---|---|
/access.log | access.log |
access.log | access.log logs/access.log var/logs/access.log |
build/ | build |
Подстановочные символы
* — символ звездочки соответствует нулю или более символам.
Шаблон | Примеры совпадений |
---|---|
*.log | error.log logs/debug.log build/logs/error.log |
** — Два соседних символа звездочки соответствуют любому файлу или нулю или более каталогам. Если за ним следует косая черта ( / ), он соответствует только каталогам.
? — Знак вопроса соответствует любому одиночному символу.
Шаблон | Примеры совпадений |
---|---|
access?.log | access0.log access1.log accessA.log |
foo?? | fooab foo23 foo0s |
Квадратных скобок
Шаблон | Примеры совпадений |
---|---|
*.[oa] | file.o file.a |
*.[!oa] | file.s file.1 file.0 |
access.2.log | access.0.log access.1.log access.2.log |
file.[ac].out | file.a.out file.b.out file.c.out |
file.[a-cx-z].out | file.a.out file.b.out file.c.out file.x.out file.y.out file.z.out |
access.[!0-2].log | access.3.log access.4.log access.Q.log |
Отрицательные паттерны
Шаблон | Примеры совпадений |
---|---|
*.log !error.log | error.log или logs/error.log не будут проигнорированы |
.gitignore Пример
Шаблоны, определенные в файлах, которые находятся в каталогах (подкаталогах) более низкого уровня, имеют приоритет над шаблонами в каталогах более высокого уровня.
Личные правила игнорирования
Например, вы можете использовать этот файл, чтобы игнорировать файлы, сгенерированные из ваших личных инструментов проекта.
Файл можно назвать как угодно и хранить в любом месте. Чаще всего этот файл хранится в домашнем каталоге. Вам придется вручную создать файл и настроить Git для его использования.
Например, чтобы установить
/.gitignore_global в качестве глобального файла игнорирования Git, вы должны сделать следующее:
Добавьте файл в конфигурацию Git:
Откройте файл в текстовом редакторе и добавьте в него свои правила.
Глобальные правила особенно полезны для игнорирования определенных файлов, которые вы никогда не хотите фиксировать, например файлов с конфиденциальной информацией или скомпилированных исполняемых файлов.
Игнорирование ранее зафиксированных файлов
Файлы в вашей рабочей копии можно отслеживать или нет.
Например, чтобы проверить, почему файл www/yarn.lock игнорируется, вы должны запустить:
Команда также принимает в качестве аргументов более одного имени файла, и файл не обязательно должен существовать в вашем рабочем дереве.
Отображение всех игнорируемых файлов
Выводы
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
How do I ignore files in a directory in Git?
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
PATTERN FORMAT
A blank line matches no files, so it can serve as a separator for readability.
A line starting with # serves as a comment.
If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).
You can find more here
git help gitignore
or
man gitignore
It would be the former. Go by extensions as well instead of folder structure.
I.e. my example C# development ignore file:
Update
Community wiki (constantly being updated):
More examples with specific language use can be found here (thanks to Chris McKnight’s comment):
Your wildcards are also redundant. If you want to ignore an entire directory, simply name it:
The only reason to use wildcards the way you have is if you intend to subsequently un-ignore something in the directory:
E.g. to ignore all *.map files in a /src/main/ folder and sub-folders use:
Both examples in the question are actually very bad examples that can lead to data loss!
A good reason would be for example what Jefromi wrote: «if you intend to subsequently un-ignore something in the directory».
The reason why it otherwise shouldn’t be done is that appending /* to directories does on the one hand work in the manner that it properly ignores all contents of the directory, but on the other hand it has a dangerous side effect:
Some background
How to reproduce
Here is how to reproduce the behaviour. I’m currently using Git 2.8.4.
In both cases the allegedly ignored directory localdata will be gone!
Not sure if this can be considered a bug, but I guess it’s at least a feature that nobody needs.
I’ll report that to the git development list and see what they think about it.
How does gitignore work?
So let’s say I have a Master Folder currently in Production and inside it there’s a reports folder that I don’t really need to track.
Now, I wanted to modify the folder so I clone the Master Folder in my repository. Does the reports folder gets cloned too?
While I’m editing, some person added or changed files inside the reports folder.
After I finish editing, I need to update the Master Folder to what I’ve updated. If I git push my changes, will it affect the Reports Folder in the Master Folder?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you want to exclude specific files, you can do something like
Assuming thst the reports are mixed file extensions but you want to ignore all word file reports from the folder.
About cloning, if someone tries to clone the project, he won’t get any report files as they were not committed at first place. Also, making any changes in the Reports folder won’t be tracked by git any more.
now if you push your master folder then git will not track your Reports folder.
Like wise you can add file name or extensions which you want to exclude. Each line in a gitignore file specifies a pattern. When deciding whether to ignore a path, Git normally checks gitignore patterns from multiple sources, with the following order of precedence, from highest to lowest (within one level of precedence, the last matching pattern decides the outcome):
Patterns read from the command line for those commands that support them.