I have a .gitignore
file, and it’s ignoring some files. I have updated the .gitignore
file (removed some filenames and added some filenames). This is not reflected in git status
. How can I force git to update these changes, so that track files which are not tracked before and vice versa.
I have tried this question, still all of my files are not tracked (according to my updated .gitignore
). (In simple, how can I force git to retract files once .gitignore
is updated or deleted).
asked Jul 19, 2016 at 5:36
2
You will have to clear the existing git cache
first.
Remove the cache of all the files
git rm -r --cached .
Remove the cache of specific file
git rm -r --cached <file_name.ext>
Once you clear the existing cache, add/stage file/files in the current directory and commit
git add .
// To add all the filesgit add <file_name.ext>
// To add specific filegit commit -m "Suitable Message"
As pointed out by Scott Biggs in comment that «This works for both adding a file that was once ignored as well as ignoring a file that was once tracked»
answered Jul 19, 2016 at 6:40
Shravan40Shravan40
8,4225 gold badges28 silver badges46 bronze badges
6
It works
//First commit any outstanding code changes, and then, run this command:
git rm -r --cached .
//This removes any changed files from the index(staging area), then just run:
git add .
//Commit
git commit -m "Atualizando .gitignore para..."
answered Jan 29, 2020 at 17:49
NajathiNajathi
2,20123 silver badges23 bronze badges
1
If you want to add all files, delete all filenames from .gitignore
file, not the .gitignore
file and commit
it, then try
git config --global core.excludesfile ~/.gitignore_global
Some files are ignored by the git depending on the OS (like .dll in windows). For more information.
Now
git add .
git status
git commit -m "your message"
Or
You can try a simple hack, it may or may not work. Delete all filenames from .gitignore
file and add this line !*.*
, then add
and commit
.
UPDATE
Simple, I’ll explain with an example. Say you have a build
folder which is already added and tracked by git. Now you decide not to track this folder.
- Add this folder (
build
) to.gitignore
- Delete
build
folder - Commit your changes
From now on git will not track build
folder.
answered Jul 19, 2016 at 11:47
3
You can resolve this issue by deleting the cache of those specific files where you are getting this issue.
The issue you mentioned occurs when you have committed some specific files once and then you are adding them in .gitignore later.
git rm -r --cached <your_file.extension>
git commit -am "Suitable Message"
Same solution is proposed by @sharvan40 above, but you don’t need to remove the cache for all the files. It creates a new commit for all your files.
answered May 27, 2018 at 13:58
Assuming here that your current working directory is empty.
You can check what files git is currently tracking by using git ls-files
. If you have a lot of files, you can use git ls-files | grep hello.txt
to find if git is tracking that specific file.
If it is tracking it, then use git rm hello.txt
to untrack it (as Tim mentioned in his comment). Perhaps commit that untracked state first and then add it in to your .gitignore
on your next commit. I have seen some funky behavior in the past when trying to ignore and remove in the same commit.
answered Jul 19, 2016 at 6:41
VidurVidur
1,4322 gold badges19 silver badges37 bronze badges
Configuring ignored files for a single repository
You can create a .gitignore file in your repository’s root directory to tell Git which files and directories to ignore when you make a commit.
To share the ignore rules with other users who clone the repository, commit the .gitignore file in to your repository.
GitHub maintains an official list of recommended .gitignore files for many popular operating systems, environments, and languages in the github/gitignore
public repository. You can also use gitignore.io to create a .gitignore file for your operating system, programming language, or IDE. For more information, see «github/gitignore» and the «gitignore.io» site.
-
Open TerminalTerminalGit Bash.
-
Navigate to the location of your Git repository.
-
Create a .gitignore file for your repository.
$ touch .gitignore
If the command succeeds, there will be no output.
For an example .gitignore file, see «Some common .gitignore configurations» in the Octocat repository.
If you want to ignore a file that is already checked in, you must untrack the file before you add a rule to ignore it. From your terminal, untrack the file.
$ git rm --cached FILENAME
Configuring ignored files for all repositories on your computer
You can also create a global .gitignore file to define a list of rules for ignoring files in every Git repository on your computer. For example, you might create the file at ~/.gitignore_global and add some rules to it.
- Open TerminalTerminalGit Bash.
- Configure Git to use the exclude file ~/.gitignore_global for all Git repositories.
$ git config --global core.excludesfile ~/.gitignore_global
Excluding local files without creating a .gitignore file
If you don’t want to create a .gitignore file to share with others, you can create rules that are not committed with the repository. You can use this technique for locally-generated files that you don’t expect other users to generate, such as files created by your editor.
Use your favorite text editor to open the file called .git/info/exclude within the root of your Git repository. Any rule you add here will not be checked in, and will only ignore files for your local repository.
- Open TerminalTerminalGit Bash.
- Navigate to the location of your Git repository.
- Using your favorite text editor, open the file .git/info/exclude.
Further Reading
- Ignoring files in the Git documentation
- .gitignore in the Git documentation
- A collection of useful .gitignore templates in the github/gitignore repository
- gitignore.io site
Git рассматривает каждый файл в вашей рабочей копии как файл одного из трех нижеуказанных типов.
- Отслеживаемый файл — файл, который был предварительно проиндексирован или зафиксирован в коммите.
- Неотслеживаемый файл — файл, который не был проиндексирован или зафиксирован в коммите.
- Игнорируемый файл — файл, явным образом помеченный для Git как файл, который необходимо игнорировать.
Игнорируемые файлы — это, как правило, артефакты сборки и файлы, генерируемые машиной из исходных файлов в вашем репозитории, либо файлы, которые по какой-либо иной причине не должны попадать в коммиты. Вот некоторые распространенные примеры таких файлов:
- кэши зависимостей, например содержимое
/node_modules
или/packages
; - скомпилированный код, например файлы
.o
,.pyc
и.class
; - каталоги для выходных данных сборки, например
/bin
,/out
или/target
; - файлы, сгенерированные во время выполнения, например
.log
,.lock
или.tmp
; - скрытые системные файлы, например
.DS_Store
илиThumbs.db
; - личные файлы конфигурации IDE, например
.idea/workspace.xml
.
Игнорируемые файлы отслеживаются в специальном файле .gitignore
, который регистрируется в корневом каталоге репозитория. В Git нет специальной команды для указания игнорируемых файлов: вместо этого необходимо вручную отредактировать файл .gitignore
, чтобы указать в нем новые файлы, которые должны быть проигнорированы. Файлы .gitignore
содержат шаблоны, которые сопоставляются с именами файлов в репозитории для определения необходимости игнорировать эти файлы.
- Игнорирование файлов в Git
- Шаблоны игнорирования в Git
- Общие файлы .gitignore в вашем репозитории
- Персональные правила игнорирования в Git
- Глобальные правила игнорирования в Git
- Игнорирование ранее закоммиченного файла
- Коммит игнорируемого файла
- Скрытие изменений в игнорируем файле
- Отладка файлов .gitignore
Шаблоны игнорирования в Git
Для сопоставления с именами файлов в .gitignore
используются шаблоны подстановки. С помощью различных символов можно создавать собственные шаблоны.
Шаблон | Примеры соответствия | Пояснение* |
---|---|---|
**/logs |
logs/debug.log logs/monday/foo.bar build/logs/debug.log |
Добавьте в начало шаблона две звездочки, чтобы сопоставлять каталоги в любом месте репозитория. |
**/logs/debug.log |
logs/debug.log build/logs/debug.log но не logs/build/debug.log |
Две звездочки можно также использовать для сопоставления файлов на основе их имени и имени родительского каталога. |
*.log |
debug.log foo.log .log logs/debug.log |
Одна звездочка — это подстановочный знак, который может соответствовать как нескольким символам, так и ни одному. |
*.log !important.log |
debug.log trace.log но не important.log logs/important.log |
Добавление восклицательного знака в начало шаблона отменяет действие шаблона. Если файл соответствует некоему шаблону, но при этом также соответствует отменяющему шаблону, указанному после, такой файл не будет игнорироваться. |
*.log !important/*.log trace.* |
debug.log important/trace.log но не important/debug.log |
Шаблоны, указанные после отменяющего шаблона, снова будут помечать файлы как игнорируемые, даже если ранее игнорирование этих файлов было отменено. |
/debug.log |
debug.log но не logs/debug.log |
Косая черта перед именем файла соответствует файлу в корневом каталоге репозитория. |
debug.log |
debug.log logs/debug.log |
По умолчанию шаблоны соответствуют файлам, находящимся в любом каталоге |
debug?.log |
debug0.log debugg.log но не debug10.log |
Знак вопроса соответствует строго одному символу. |
debug[0-9].log |
debug0.log debug1.log но не debug10.log |
Квадратные скобки можно также использовать для указания соответствия одному символу из заданного диапазона. |
debug[01].log |
debug0.log debug1.log но не debug2.log debug01.log |
Квадратные скобки соответствуют одному символу из указанного набора. |
debug[!01].log |
debug2.log но не debug0.log debug1.log debug01.log |
Восклицательный знак можно использовать для указания соответствия любому символу, кроме символов из указанного набора. |
debug[a-z].log |
debuga.log debugb.log но не debug1.log |
Диапазоны могут быть цифровыми или буквенными. |
logs |
logs logs/debug.log logs/latest/foo.bar build/logs build/logs/debug.log |
Без косой черты в конце этот шаблон будет соответствовать и файлам, и содержимому каталогов с таким именем. В примере соответствия слева игнорируются и каталоги, и файлы с именем logs |
logs/ | logs/debug.log logs/latest/foo.bar build/logs/foo.bar build/logs/latest/debug.log |
Косая черта в конце шаблона означает каталог. Все содержимое любого каталога репозитория, соответствующего этому имени (включая все его файлы и подкаталоги), будет игнорироваться |
logs/ !logs/important.log |
logs/debug.log logs/important.log |
Минуточку! Разве файл logs/important.log из примера слева не должен быть исключен нз списка игнорируемых?
Нет! Из-за странностей Git, связанных с производительностью, вы не можете отменить игнорирование файла, которое задано шаблоном соответствия каталогу |
logs/**/debug.log |
logs/debug.log logs/monday/debug.log logs/monday/pm/debug.log |
Две звездочки соответствуют множеству каталогов или ни одному. |
logs/*day/debug.log |
logs/monday/debug.log logs/tuesday/debug.log but not logs/latest/debug.log |
Подстановочные символы можно использовать и в именах каталогов. |
logs/debug.log |
logs/debug.log но не debug.log build/logs/debug.log |
Шаблоны, указывающие на файл в определенном каталоге, задаются относительно корневого каталога репозитория. (При желании можно добавить в начало косую черту, но она ни на что особо не повлияет.) |
Две звездочки (**) означают, что ваш файл .gitignore находится в каталоге верхнего уровня вашего репозитория, как указано в соглашении. Если в репозитории несколько файлов .gitignore, просто мысленно поменяйте слова «корень репозитория» на «каталог, содержащий файл .gitignore» (и подумайте об объединении этих файлов, чтобы упростить работу для своей команды)*.
Помимо указанных символов, можно использовать символ #, чтобы добавить в файл .gitignore
комментарии:
Если у вас есть файлы или каталоги, в имени которых содержатся спецсимволы шаблонов, для экранирования этих спецсимволов в .gitignore
можно использовать обратную косую черту ():
# ignore the file literally named foo[01].txt
foo[01].txt
Обычно правила игнорирования Git задаются в файле .gitignore
в корневом каталоге репозитория. Тем не менее вы можете определить несколько файлов .gitignore
в разных каталогах репозитория. Каждый шаблон из конкретного файла .gitignore
проверяется относительно каталога, в котором содержится этот файл. Однако проще всего (и этот подход рекомендуется в качестве общего соглашения) определить один файл .gitignore
в корневом каталоге. После регистрации файла .gitignore
для него, как и для любого другого файла в репозитории, включается контроль версий, а после публикации с помощью команды push он становится доступен остальным участникам команды. В файл .gitignore
, как правило, включаются только те шаблоны, которые будут полезны другим пользователям репозитория.
Персональные правила игнорирования в Git
В специальном файле, который находится в папке .git/info/exclude
, можно определить персональные шаблоны игнорирования для конкретного репозитория. Этот файл не имеет контроля версий и не распространяется вместе с репозиторием, поэтому он хорошо подходит для указания шаблонов, которые будут полезны только вам. Например, если у вас есть пользовательские настройки для ведения журналов или специальные инструменты разработки, которые создают файлы в рабочем каталоге вашего репозитория, вы можете добавить их в .git/info/exclude
, чтобы они случайно не попали в коммит в вашем репозитории.
Глобальные правила игнорирования в Git
Кроме того, для всех репозиториев в локальной системе можно определить глобальные шаблоны игнорирования Git, настроив параметр конфигурации Git core.excludesFile
. Этот файл нужно создать самостоятельно. Если вы не знаете, куда поместить глобальный файл .gitignore
, расположите его в домашнем каталоге (потом его будет легче найти). После создания этого файла необходимо настроить его местоположение с помощью команды git config
:
$ touch ~/.gitignore
$ git config --global core.excludesFile ~/.gitignore
Будьте внимательны при указании глобальных шаблонов игнорирования, поскольку для разных проектов актуальны различные типы файлов. Типичные кандидаты на глобальное игнорирование — это специальные файлы операционной системы (например, .DS_Store
и thumbs.db
) или временные файлы, создаваемые некоторыми инструментами разработки.
Игнорирование ранее закоммиченного файла
Чтобы игнорировать файл, для которого ранее был сделан коммит, необходимо удалить этот файл из репозитория, а затем добавить для него правило в .gitignore
. Используйте команду git rm
с параметром --cached
, чтобы удалить этот файл из репозитория, но оставить его в рабочем каталоге как игнорируемый файл.
$ echo debug.log >> .gitignore $ git rm --cached debug.log
rm 'debug.log'
$ git commit -m "Start ignoring debug.log"
Опустите опцию --cached
, чтобы удалить файл как из репозитория, так и из локальной файловой системы.
Коммит игнорируемого файла
Можно принудительно сделать коммит игнорируемого файла в репозиторий с помощью команды git add
с параметром -f
(или --force
):
$ cat .gitignore
*.log $ git add -f debug.log
$ git commit -m "Force adding debug.log"
Этот способ хорош, если у вас задан общий шаблон (например, *.log
), но вы хотите сделать коммит определенного файла. Однако еще лучше в этом случае задать исключение из общего правила:
$ echo !debug.log >> .gitignore $ cat .gitignore
*.log
!debug.log
$ git add debug.log
$ git commit -m "Adding debug.log"
Этот подход более прозрачен и понятен, если вы работаете в команде.
Скрытие изменений в игнорируем файле
Команда git stash
— это мощная функция системы Git, позволяющая временно отложить и отменить локальные изменения, а позже применить их повторно. По умолчанию команда git stash
ожидаемо не обрабатывает игнорируемые файлы и создает отложенные изменения только для тех файлов, которые отслеживаются Git. Тем не менее вы можете вызвать команду git stash с параметром —all, чтобы создать отложенные изменения также для игнорируемых и неотслеживаемых файлов.
Отладка файлов .gitignore
Если шаблоны .gitignore
сложны или разбиты на множество файлов .gitignore
, бывает непросто отследить, почему игнорируется определенный файл. Используйте команду git check-ignore
с параметром -v
(или --verbose
), чтобы определить, какой шаблон приводит к игнорированию конкретного файла:
$ git check-ignore -v debug.log
.gitignore:3:*.log debug.log
Вывод показывает:
<file containing the pattern> : <line number of the pattern> : <pattern> <file name>
При желании команде git check-ignore
можно передать несколько имен файлов, причем сами имена могут даже не соответствовать файлам, существующим в вашем репозитории.
NAME
gitignore — Specifies intentionally untracked files to ignore
SYNOPSIS
$XDG_CONFIG_HOME/git/ignore, $GIT_DIR/info/exclude, .gitignore
DESCRIPTION
A gitignore
file specifies intentionally untracked files that
Git should ignore.
Files already tracked by Git are not affected; see the NOTES
below for details.
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. -
Patterns read from a
.gitignore
file in the same directory
as the path, or in any parent directory (up to the top-level of the working
tree), with patterns in the higher level files being overridden by those in
lower level files down to the directory containing the file. These patterns
match relative to the location of the.gitignore
file. A project normally
includes such.gitignore
files in its repository, containing patterns for
files generated as part of the project build. -
Patterns read from
$GIT_DIR/info/exclude
. -
Patterns read from the file specified by the configuration
variablecore.excludesFile
.
Which file to place a pattern in depends on how the pattern is meant to
be used.
-
Patterns which should be version-controlled and distributed to
other repositories via clone (i.e., files that all developers will want
to ignore) should go into a.gitignore
file. -
Patterns which are
specific to a particular repository but which do not need to be shared
with other related repositories (e.g., auxiliary files that live inside
the repository but are specific to one user’s workflow) should go into
the$GIT_DIR/info/exclude
file. -
Patterns which a user wants Git to
ignore in all situations (e.g., backup or temporary files generated by
the user’s editor of choice) generally go into a file specified by
core.excludesFile
in the user’s~/.gitconfig
. Its default value is
$XDG_CONFIG_HOME/git/ignore. If $XDG_CONFIG_HOME is either not set or
empty, $HOME/.config/git/ignore is used instead.
The underlying Git plumbing tools, such as
git ls-files and git read-tree, read
gitignore
patterns specified by command-line options, or from
files specified by command-line options. Higher-level Git
tools, such as git status and git add,
use patterns from the sources specified above.
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.
Put a backslash (««) in front of the first hash for patterns
that begin with a hash. -
Trailing spaces are ignored unless they are quoted with backslash
(««).
-
An optional prefix «
!
» which negates the pattern; any
matching file excluded by a previous pattern will become
included again. It is not possible to re-include a file if a parent
directory of that file is excluded. Git doesn’t list excluded
directories for performance reasons, so any patterns on contained
files have no effect, no matter where they are defined.
Put a backslash (««) in front of the first «
!
» for patterns
that begin with a literal «!
«, for example, «!important!.txt
«. -
The slash / is used as the directory separator. Separators may
occur at the beginning, middle or end of the.gitignore
search pattern. -
If there is a separator at the beginning or middle (or both) of the
pattern, then the pattern is relative to the directory level of the
particular.gitignore
file itself. Otherwise the pattern may also
match at any level below the.gitignore
level. -
If there is a separator at the end of the pattern then the pattern
will only match directories, otherwise the pattern can match both
files and directories. -
For example, a pattern
doc/frotz/
matchesdoc/frotz
directory,
but nota/doc/frotz
directory; howeverfrotz/
matchesfrotz
anda/frotz
that is a directory (all paths are relative from
the.gitignore
file). -
An asterisk «
*
» matches anything except a slash.
The character «?
» matches any one character except «/
«.
The range notation, e.g.[a-zA-Z]
, can be used to match
one of the characters in a range. See fnmatch(3) and the
FNM_PATHNAME flag for a more detailed description.
Two consecutive asterisks («**
«) in patterns matched against
full pathname may have special meaning:
-
A leading «
**
» followed by a slash means match in all
directories. For example, «**/foo
» matches file or directory
«foo
» anywhere, the same as pattern «foo
«. «**/foo/bar
»
matches file or directory «bar
» anywhere that is directly
under directory «foo
«. -
A trailing «
/**
» matches everything inside. For example,
«abc/**
» matches all files inside directory «abc
«, relative
to the location of the.gitignore
file, with infinite depth. -
A slash followed by two consecutive asterisks then a slash
matches zero or more directories. For example, «a/**/b
»
matches «a/b
«, «a/x/b
«, «a/x/y/b
» and so on. -
Other consecutive asterisks are considered regular asterisks and
will match according to the previous rules.
CONFIGURATION
The optional configuration variable core.excludesFile
indicates a path to a
file containing patterns of file names to exclude, similar to
$GIT_DIR/info/exclude
. Patterns in the exclude file are used in addition to
those in $GIT_DIR/info/exclude
.
NOTES
The purpose of gitignore files is to ensure that certain files
not tracked by Git remain untracked.
To stop tracking a file that is currently tracked, use
git rm —cached.
Git does not follow symbolic links when accessing a .gitignore
file in
the working tree. This keeps behavior consistent when the file is
accessed from the index or a tree versus from the filesystem.
EXAMPLES
-
The pattern
hello.*
matches any file or directory
whose name begins withhello.
. If one wants to restrict
this only to the directory and not in its subdirectories,
one can prepend the pattern with a slash, i.e./hello.*
;
the pattern now matcheshello.txt
,hello.c
but not
a/hello.java
. -
The pattern
foo/
will match a directoryfoo
and
paths underneath it, but will not match a regular file
or a symbolic linkfoo
(this is consistent with the
way how pathspec works in general in Git) -
The pattern
doc/frotz
and/doc/frotz
have the same effect
in any.gitignore
file. In other words, a leading slash
is not relevant if there is already a middle slash in
the pattern. -
The pattern «foo/*», matches «foo/test.json»
(a regular file), «foo/bar» (a directory), but it does not match
«foo/bar/hello.c» (a regular file), as the asterisk in the
pattern does not match «bar/hello.c» which has a slash in it.
$ git status [...] # Untracked files: [...] # Documentation/foo.html # Documentation/gitignore.html # file.o # lib.a # src/internal.o [...] $ cat .git/info/exclude # ignore objects and archives, anywhere in the tree. *.[oa] $ cat Documentation/.gitignore # ignore generated html files, *.html # except foo.html which is maintained by hand !foo.html $ git status [...] # Untracked files: [...] # Documentation/foo.html [...]
Another example:
$ cat .gitignore vmlinux* $ ls arch/foo/kernel/vm* arch/foo/kernel/vmlinux.lds.S $ echo '!/vmlinux*' >arch/foo/kernel/.gitignore
The second .gitignore prevents Git from ignoring
arch/foo/kernel/vmlinux.lds.S
.
Example to exclude everything except a specific directory foo/bar
(note the /*
— without the slash, the wildcard would also exclude
everything within foo/bar
):
$ cat .gitignore # exclude everything except directory foo/bar /* !/foo /foo/* !/foo/bar