Как написать gitignore

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
    variable core.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/ matches doc/frotz directory,
    but not a/doc/frotz directory; however frotz/ matches frotz
    and a/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 with hello.. 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 matches hello.txt, hello.c but not
    a/hello.java.

  • The pattern 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)

  • 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

SEE ALSO

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.

  1. Open TerminalTerminalGit Bash.

  2. Navigate to the location of your Git repository.

  3. 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.

  1. Open TerminalTerminalGit Bash.
  2. 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.

  1. Open TerminalTerminalGit Bash.
  2. Navigate to the location of your Git repository.
  3. 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 рассматривает каждый файл в вашей рабочей копии как файл одного из трех нижеуказанных типов.

  1. Отслеживаемый файл — файл, который был предварительно проиндексирован или зафиксирован в коммите.
  2. Неотслеживаемый файл — файл, который не был проиндексирован или зафиксирован в коммите.
  3. Игнорируемый файл — файл, явным образом помеченный для 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 можно передать несколько имен файлов, причем сами имена могут даже не соответствовать файлам, существующим в вашем репозитории.

Файл .gitignore используется для того, чтобы определить, какие файлы и папки не нужно добавлять в git репозиторий.

Мы конечно могли бы вручную добавлять нужные файлы в репозиторий, например так:

git add path/to/file

Однако это было бы очень трудоемко. Гораздо проще использовать команду:

git add .

Которая добавит все файлы в каталоге проекта.

Но что если нам не нужны абсолютно все файлы, а есть файлы например в каталоге /cache или /images или /runtime проекта, которые генерируются в процессе работы. Они не должны быть добавлены в репозиторий.

Тут нам и нужен .gitignore. Вам нужно его самим создать и разместить в корне проекта либо нужной подпапке.

Где должен находиться этот файл

Файл может находиться в корне проекта или любом подкаталоге.

Либо можно задать глобальный файл gitignore, таким образом:

$ git config --global core.excludesfile ~/.gitignore_global

Таким образом вы сможете записать в глобальный файл ~/.gitignore_global настройки, общие для всех ваших проектов. В нем могут храниться например файлы для игнорирования, которые специфичны для вашей IDE, и по этому не логично добавлять их в репозиторий.
Однако файлы, которые специфичны для конкретного проекта, обязательно нужно добавлять в .gitignore самого проекта.

Примеры содержимого .gitignore файла

# строки начинающиеся на # - это комментарии, они не учитываются

# Исключить все файлы с расширение .a
*.a

# Но отслеживать файл lib.a даже если он подпадает под исключение выше
!lib.a

# Исключить файл TODO в корневом каталоге, но не файл в subdir/TODO
/TODO

# Игнорировать все файлы в каталоге build/
build/

# Игнорировать файл doc/notes.txt, но не файл doc/server/arch.txt
doc/*.txt

# Игнорировать все .txt файлы в каталоге doc/
doc/**/*.txt

Подробнее о шаблонах игнорирования

Шаблон Примеры соответствия Пояснение*
**/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 уже добавлены в репозиторий

Обратите внимание, что если файлы уже добавлены в git репозиторий, то добавление их в .gitignore не удалит эти файлы.
Изменения в них будут продолжать отслеживаться и входить в коммиты, несмотря на то, что они есть в .gitignore.

Нам придется вручную их удалить из репозитория.

Очень удобная команда bash, которая удалит из git репозитория те файлы, которые содержатся в файлах .gitignore:

git rm --cached `git ls-files -i --exclude-from=.gitignore`

То же самое для Powershell

foreach ($i in iex 'git ls-files -i --exclude-from=.gitignore') { git rm --cached $i }

При выполнении этой команды, файлы останутся у вас на диске, однако из репозитория они будут удалены.

Либо можно удалять файлы вручную, таким образом:

git rm --cached path/to/file

Либо если нам нужно удалить целую директорию из git, то воспользуемся следующей командой:

git rm  -r --cached path/to/directory

Либо так мы могли бы удалить все файлы с расширением .log в папке log:

git rm --cached log/*.log

Параметр --cached означает, что файлы будут удалены только из раздела «проиндексированных файлов».
На диске (рабочем каталоге) они останутся нетронутыми.

Как понять, почему игнорируется конкретный файл

Запустите команду вместо path/to/file следует указать путь к файлу.

git check-ignore -v path/to/file

В итоге мы получим ответ, в котором содержится конкретная строка .gitignore, благодаря которой данный файл игнорируется.

Отобразить все игнорируемые файлы:

git status --ignored

Очистить проект от всех игнорируемых файлов:

git clean -fX

Используйте с осторожностью. Убедитесь что у вас есть резервная копия.

Документация

Читайте подробную документацию по этой ссылке: https://git-scm.com/docs/gitignore

Нашли опечатку или ошибку? Выделите её и нажмите Ctrl+Enter

Помогла ли Вам эта статья?

.gitignore File – How to Ignore Files and Folders in Git

Git is a popular version control system. It is how developers can collaborate and work together on projects.

Git allows you to track the changes you make to your project over time. On top of that, it lets you revert to a previous version if you want to undo a change.

The way Git works is that you stage files in a project with the git add command and then commit them with the git commit command.

When working on a project as part of a team, there will be times when you don’t want to share some files or parts of the project with others.

In other words, you don’t want to include or commit those specific files to the main version of the project. This is why you may not want to use the period . with the git add command as this stages every single file in the current Git directory.

When you use the git commit command, every single file gets committed – this also includes files that do not need to be or shouldn’t be.

You may instead want Git to ignore specific files, but there is no git ignore command for that purpose.

So, how do you tell Git to ignore and not track specific files? With a .gitignore file.

In this article, you will learn what a .gitignore file is, how to create one, and how to use it to ignore files and folders. You will also see how you can ignore a previously committed file.

Here is what we will cover:

  1. What is a .gitignore file?
    1. How to create a .gitignore file
    2. What to Include in a .gitignore file?
  2. How to ignore a file and folder in Git
    1. How to ignore a previously committed file

What Is a .gitignore File? What Is a .gitignore File Used For?

Each of the files in any current working Git repository is either:

  • tracked – these are all the files or directories Git knows about. These are the files and directories newly staged (added with git add) and committed (committed with git commit) to the main repo.
  • untracked – these are any new files or directories created in the working directory but that have not yet been staged (or added using the git add command).
  • ignored – these are all the files or directories that Git knows to completely exclude, ignore, and not be aware of in the Git repository. Essentially, this is a way to tell Git which untracked files should remain untracked and never get committed.

All ignored files get stored in a .gitignore file.

A .gitignore file is a plain text file that contains a list of all the specified files and folders from the project that Git should ignore and not track.

Inside .gitignore, you can tell Git to ignore only a single file or a single folder by mentioning the name or pattern of that specific file or folder. You can also tell Git to ignore multiple files or folders using the same method.

How to Create a .gitignore File

Typically, a .gitignore file gets placed in the root directory of the repository. The root directory is also known as the parent and the current working directory. The root folder contains all the files and other folders that make up the project.

That said, you can place it in any folder in the repository. You can even have multiple .gitignore files, for that matter.

To create a .gitignore file on a Unix-based system such as macOS or Linux using the command line, open the terminal application (such as Terminal.app on macOS). Then, navigate to the root folder that contains the project using the cd command and enter the following command to create a .gitignore file for your directory:

touch .gitignore

Files with a dot (.) preceding their name are hidden by default.

Hidden files are not visible when using the ls command alone. To view all files – including hidden ones – from the command line, use the -a flag with the ls command like so:

ls -a

What to Include in a .gitignore File

The types of files you should consider adding to a .gitignore file are any files that do not need to get committed.

You may not want to commit them for security reasons or because they are local to you and therefore unnecessary for other developers working on the same project as you.

Some of these may include:

  • Operating System files. Each Operating System (such as macOS, Windows, and Linux) generates system-specific hidden files that other developers don’t need to use since their system also generates them. For example, on macOS, Finder generates a .DS_Store file that includes user preferences for the appearance and display of folders, such as the size and position of icons.
  • Configuration files generated by applications such as code editors and IDEs (IDE stands for Integrated Development Environment). These files are custom to you, your configurations, and your preferences settings.
  • Files that get automatically generated from the programming language or framework you are using in your project and compiled code-specific files, such as .o files.
  • Folders generated by package managers, such as npm’s node_modules folder. This is a folder used for saving and tracking the dependencies for each package you install locally.
  • Files that contain sensitive data and personal information. Some examples of such files are files with your credentials (username and password) and files with environment variables like .env files (.env files contain API keys that need to remain secure and private).
  • Runtime files, such as .log files. They provide information on the Operating System’s usage activities and errors, as well as a history of events that have taken place within the OS.

How to Ignore a File and Folder in Git

If you want to ignore only one specific file, you need to provide the full path to the file from the root of the project.

For example, if you want to ignore a text.txt file located in the root directory, you would do the following:

/text.txt

And if you wanted to ignore a text.txt file located in a test directory at the root directory, you would do the following:

/test/text.txt

You could also write the above like so:

test/text.txt

If you want to ignore all files with a specific name, you need to write the literal name of the file.

For example, if you wanted to ignore any text.txt files, you would add the following to .gitignore:

text.txt

In this case, you don’t need to provide the full path to a specific file. This pattern will ignore all files with that particular name that are located anywhere in the project.

To ignore an entire directory with all its contents, you need to include the name of the directory with the slash / at the end:

test/

This command will ignore any directory (including other files and other sub-directories inside the directory) named test located anywhere in your project.

Something to note is that if you write the name of a file alone or the name of the directory alone without the slash /, then this pattern will match both any files or directories with that name:

# matches any files and directories with the name test
test

What if you want to ignore any files or directories that start with a specific word?

Say that you want to ignore all files and directories that have a name starting with img. To do this, you would need to specify the name you want to ignore followed by the * wildcard selector like so:

img*

This command will ignore all files and directories that have a name starting with img.

But what if you want to ignore any files or directories that end with a specific word?

If you wanted to ignore all files that end with a specific file extension, you would need to use the * wildcard selector followed by the file extension you want to ignore.

For example, if you wanted to ignore all markdown files that end with a .md file extension, you would add the following to your .gitignore file:

*.md

This pattern will match any file ending with the .md extension located anywhere in the project.

Earlier, you saw how to ignore all files ending with a specific suffix. What happens when you want to make an exception, and there is one file with that suffix that you don’t want to ignore?

Say you added the following to your .gitignore file:

.md

This pattern ignores all files ending in .md, but you don’t want Git to ignore a README.md file.

To do this, you would need to use the negating pattern with an exclamation mark, !, to negate a file that would otherwise be ignored:

# ignores all .md files
.md

# does not ignore the README.md file
!README.md

With both of those patterns in the .gitignore file, all files ending in .md get ignored except for the README.md file.

Something to keep in mind is that this pattern will not work if you ignore an entire directory.

Say that you ignore all test directories:

test/

Say that inside a test folder, you have a file, example.md, that you don’t want to ignore.

You cannot negate a file inside an ignored directory like so:

# ignore all directories with the name test
test/

# trying to negate a file inside an ignored directory won't work
!test/example.md

How to Ignore a Previously Committed File

It’s a best practice to create a .gitignore file with all the files and the different file patterns you want to ignore when you create a new repository – before committing it.

Git can only ignore untracked files that haven’t yet been committed to the repository.

What happens when you have already committed a file in the past and wish you hadn’t?

Say you accidentally committed a .env file that stores environment variables.

You first need to update the .gitignore file to include the .env file:

# add .env file to .gitignore
echo ".env" >> .gitignore

Now, you will need to tell Git not to track this file by removing it from the index:

git rm --cached .env

The git rm command, along with the --cached option, deletes the file from the repository but does not delete the actual file. This means the file remains on your local system and in your working directory as an ignored file.

A git status will show that the file is no longer in the repository, and entering the ls command will show that the file exists on your local file system.

If you want to delete the file from the repository and your local system, omit the --cached option.

Next, add the .gitignore to the staging area using the git add command:

git add .gitignore

Finally, commit the .gitignore file using the git commit command:

git commit -m "update ignored files"

Conclusion

And there you have it – you now know the basics of ignoring files and folders in Git.

Hopefully, you found this article helpful.

To learn more about Git, check out the following free resources:

  • Git and GitHub for Beginners — Crash Course
  • Git for Professionals Tutorial — Tools & Concepts for Mastering Version Control with Git
  • Advanced Git Tutorial — Interactive Rebase, Cherry-Picking, Reflog, Submodules and more

Thank you for reading and happy coding :)



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git relies on the basis of distributed development of software where more than one developer may have access to the source code of a specific application and can modify changes to it that may be seen by other developers. So in this article, we will cover various concepts related to ignoring files and folders in the git. We will start the article by learning how to create the .gitignore file and how it works.

Creating .gitignore and knowing about its functionalities 

Creating .gitignore file

Using git status to show the status of files

Now we can see that there are a lot of files that are in untracked files and some of them are those files that are being staged already but there are no files that are being ignored. Sounds interesting so that means that there are ignored files also in git. So to ignore a file in git we use a .gitignore file inside that file you can mention whether you want a particular file to be ignored or a file ending with a specific extension. So here in this file, we can see that *.txt is mentioned which means that all the .txt files should be ignored in this directory.

Adding which files shouldn’t be added in …gitignore

Now we will use the git status –ignored the command to see all the ignored files present in the directory. 

Using git status –ignored to see the status of ignored files

Exceptions in a.gitignore file

So how do exceptions work in the .gitignore file is we can take the example of our *.txt which we wrote in our .gitignore file which means that all the .txt files should be ignored. Also, we can write !file_name.txt which means that the particular file shouldn’t be ignored. So here we can see when *.txt was mentioned in the .gitignore file all the .txt files were ignored in the directory.

Editing the .gitignore file with !file_name.txt

Adding the !file_name.txt in the .gitignore file after adding this we can see that the file is not in ignored files now and here you can see the file_name is a.txt which previously was coming in the ignored files and now we can see that now the file is in untracked files.

Seeing the changes after adding this !a.txt in the .gitignore file

So if there are some .txt files in some folder then that folder will be ignored and we cannot easily reinclude files from that folder so there is a procedure how to reinclude all those files from that folder because here according to .gitignore all the *.txt files should be ignored except a.txt.

Using git status –ignored

Here you can see the secrets folder is in the ignored files because according to the .gitignore all the *.txt files should be ignored. So to reinclude all the *.txt files from the secrets folder we have to first reinclude the secrets folder by writing !folder_name in the .gitignore here folder_name is secrets and then we have to ignore all the files present in the secrets folder by writing secrets/* in the .gitignore and then write !secrets/*.txt to reinclude all the .txt files from the secrets folder to remove the folder from and reinclude all the .txt files in the folder from ignored files. 

Editing .gitignore file

Using git status –ignored to see whether the folder is removed from the ignored files or not

Now if our use case is to remove those files whose file_names are beginning with ! in the .gitignore file then add one more ! or add in the front of your file_name or you can also remove a folder by this who is having some files which don’t want git to have a track on them. By using these exceptions in the a.gitignore file you will move these files and folders in the ignored files.

Editing .gitignore

Using git status –ignored to see the files are in ignored files or not

A Global .gitignore file

So if our use case is that if we want specific files to be ignored by git in all repositories then we can create a global .gitignore in any of the repositories and make it global using the following command: 

git config --global core.excludesfile path_of_global_gitignore_file

Here you can see the path should be complete that is the name_of_the_drive/folder_name/.gitignore to avoid errors like this warning: unable to access permission denied fatal: cannot use as an exclude file. Now git will use this in addition to each repository’s .gitignore file. So let us see the syntax of the command:

Showing the syntax of the command: git config –global core.excludes file path_of_global_gitignore_file

So now if we edit the global .gitignore file and write *.py then it will ignore all the *.py files present in our repository. Now let’s see how this works:

Editing the global .gitignore file

So now if we use the git status –ignored command we will see all the .py files in ignored files. 

Using git status –ignored

So now if we include all these *.py files in the local .gitignore file of our repository then what will happen because our global .gitignore file ignores all the .py files. Now the question here is who will take the priority so the answer to this is our local .gitignore file takes priority always whenever there is a file that is ignored by the global .gitignore file but is included by the local .gitignore file. So we will write !*.py in our local. .gitignore file will include all the files .py files and will not put them in ignored files.

Editing the local .gitignore file

So, now we can see all the py files are now in untracked files and there are no py files that are in ignored files.

Using git status –ignored command to see whether the py files are removed from the ignored  files or not

Ignore all the files that already have been committed to a Git repository

So now if we want a file that already has been committed to the git repository and now we want that git should stop tracking it for that type of use-case we can remove it using the following command:

git rm --cached file

This will remove the file from the repository and prevent any further changes from being tracked by Git. The –cached option will make sure that the file is not physically deleted. The previously added contents of this file will still be visible but keep in mind that if anyone else pulls from the repository after the file is being removed then their copy will be physically deleted. 

Before using git rm –cached status of the file

After Using git rm –cached file  

You can make git pretend that the working tree version of the file is up to date thus ignoring changes in it with the skip-worktree option using the command.

git update-index --skip-worktree file_name

Here we can see that readme.md is modified

Here we can see that after using the above command git is ignoring any changes being done in the readme.md

Here we can see by using this above command git is not able to track any further changes in the readme.md and ignore any changes being done in the readme.md. Now to have a track of the changes in the readme.md we can use the command git update-index –no-skip-worktree file_name.

Using the command git update-index –no-skip-worktree file_name

Now we can see that on using git status we can see that readme.md is being modified and some changes need to be staged for commit. Now if you want to force git to ignore any changes made in a  file then we can use the command.

git update-index --assume-unchanged file_name 

Using the above command so that git doesn’t ignore the file

Now if we want that git shouldn’t ignore the file and again take care of it. For this, we will use the command 

git update-index --no-assume-unchanged file_name 

Using the above command so that git doesn’t ignore the file

Ignoring files locally without committing ignore rules

If you want to ignore certain files in a repository locally and not make the file part of any repository, then we will edit the .git/info/exclude inside your repository. Here we will ignore a file say rock.py and now we can see that before editing the file .git/info/exclude git is showing us the file in untracked files.

Before editing the file .git/info/exclude

Editing the file .git/info/exclude

Using git status –ignored to see the status of rock.py

Now we can see that rock.py is in ignored files now.
 

Ignoring a file in any directory 

If we want to ignore a file in any directory we have to just write its name in the  .gitignore file whether in your global or local or it can be your .git/info/exclude of the repository according to your use case. If you want that in your particular repo only a particular file in a specific directory should be ignored then you can mention the name of that file in the local.gitignore file and if you want that all the repositories should ignore the file then you can write the name of that file in global .gitignore then the file would be ignored by all the repositories.

Mentioning the name of the file .gitignore

Using git status –ignored

Here you can see the file is now in ignored files and whatever the folders were containing that file is also ignored. Now if you want to ignore a certain file in a specific folder only then we can edit the .gitignore just like this: mainfolder_name/**/file_name. Here ** denotes subdirectories. The meaning of mainfolder_name/**/file_name this line is only the file contained in this folder or its subdirectories will be ignored. But if the file is at some other location of the repository with the same name then that will not be ignored.

Editing the .gitignore

Using git status –ignored

Now we can see that the cars.cpp file created in the main folder is in the untracked files and the file cars.cpp which is present in the testing folder and its subdirectories are ignored because in the .gitignore file it is written that testing/**/cars.cpp which means all the files with cars.cpp name should be ignored in the testing folder and its subdirectories or what we can do is create a local .gitignore file in the folder where want to ignore the file. Now what are we doing is creating a local .gitignore file in the folder where we are going to ignore the file. So what we have done is we have erased this line testing/**/cars.cpp from our local .gitignore file so that we can see the effect of the .gitignore file present in our folder testing which we have newly created.

Editing the local  .gitignore

Using git status –ignored command

Now you can see that on using git status –ignored command we are seeing that cars.cpp from the testing folder and its subdirectories are ignored. 

Prefilled .gitignore Templates

Create an Empty folder

It is not possible to add and commit an empty folder in the git so to achieve this we have two methods:

Method one: .gitkeep  

So for tracking an empty folder in git we will create an empty folder inside the repository and in that folder create an empty .gitkeep file which will register the folder to git and we will be able to track the empty folder.

Checking the status of empty folder gitisfun without a .gitkeep

So now we can see that the gitisfun folder is not having any .gitkeep file and without any .gitkeep file it is not being tracked by git.  So let’s create a .gitkeep file in an empty folder so that we can track an empty folder in git.

Creating .gitkeep file in the empty folder

Adding the empty folder in the staging area

So now we can see that the empty folder is now being tracked by git. There is one more method by which we can track the empty folder in git.

Method two: dummy.txt

So to track an empty folder in git using dummy.txt, we will create an empty folder in which we will create a dummy.txt file, and in that, you can insert any funny messages you want and now after creating this dummy.txt file in the empty folder we will be able to add the empty folder in the staging area.

Without dummy.txt the empty folder is not being tracked by git

Created dummy.txt in the empty folder and now we can see that the empty folder is now being tracked by git 

Here the name of the empty folder is batman. So these are the two methods by which we can track an empty folder in git. 

Finding files ignored by .gitignore

So now if you want to see all the files ignored by git in your repository or any of the directories present in the repository we can use the following command:

git status --ignored

Using git status –ignored command

So now if you want to list recursively ignored files in directories, we will be using an additional parameter  –untracked-files=all, and the command would be:

git status --ignored --untracked-files=all

Using git status –ignored –untracked-files=all

So now we can see that it is listing all the recursively ignored files in directories also.

Ignoring changes in tracked files

So now if you are thinking of ignoring changes in tracked files then you might think that why not to use .gitignore or .git/info/exclude and just mention the name of the file which we want to ignore but .gitignore and .git/info/exclude only works for ignoring untracked files. So to ignore a tracked file we use the following command git update-index –skip-worktree file_name. So here you can see that the file try.txt which is in tracked files is modified but now after applying the command: git update-index –skip-worktree file_name any changes done in the try.txt is being ignored by the git because of the command we used.

Modifying the file try.txt

Using the command git update-index –skip-worktree file_name

So now we can see that after applying the command git update-index –skip-worktree file_name the tracked file is being ignored and now if you want to revert this we can use the following command: git update-index –no-skip-worktree file_name so this command will again make the file to be tracked by git.

Using the command git update-index –no-skip-worktree file_name

We can also use the command git update-index –assume-unchanged file_name in alternative to git update-index –skip-worktree file_name both works the same and in alternative to the command git update-index –no-skip-worktree we can use git update-index –no-assume-unchanged file_name command.

Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git relies on the basis of distributed development of software where more than one developer may have access to the source code of a specific application and can modify changes to it that may be seen by other developers. So in this article, we will cover various concepts related to ignoring files and folders in the git. We will start the article by learning how to create the .gitignore file and how it works.

Creating .gitignore and knowing about its functionalities 

Creating .gitignore file

Using git status to show the status of files

Now we can see that there are a lot of files that are in untracked files and some of them are those files that are being staged already but there are no files that are being ignored. Sounds interesting so that means that there are ignored files also in git. So to ignore a file in git we use a .gitignore file inside that file you can mention whether you want a particular file to be ignored or a file ending with a specific extension. So here in this file, we can see that *.txt is mentioned which means that all the .txt files should be ignored in this directory.

Adding which files shouldn’t be added in …gitignore

Now we will use the git status –ignored the command to see all the ignored files present in the directory. 

Using git status –ignored to see the status of ignored files

Exceptions in a.gitignore file

So how do exceptions work in the .gitignore file is we can take the example of our *.txt which we wrote in our .gitignore file which means that all the .txt files should be ignored. Also, we can write !file_name.txt which means that the particular file shouldn’t be ignored. So here we can see when *.txt was mentioned in the .gitignore file all the .txt files were ignored in the directory.

Editing the .gitignore file with !file_name.txt

Adding the !file_name.txt in the .gitignore file after adding this we can see that the file is not in ignored files now and here you can see the file_name is a.txt which previously was coming in the ignored files and now we can see that now the file is in untracked files.

Seeing the changes after adding this !a.txt in the .gitignore file

So if there are some .txt files in some folder then that folder will be ignored and we cannot easily reinclude files from that folder so there is a procedure how to reinclude all those files from that folder because here according to .gitignore all the *.txt files should be ignored except a.txt.

Using git status –ignored

Here you can see the secrets folder is in the ignored files because according to the .gitignore all the *.txt files should be ignored. So to reinclude all the *.txt files from the secrets folder we have to first reinclude the secrets folder by writing !folder_name in the .gitignore here folder_name is secrets and then we have to ignore all the files present in the secrets folder by writing secrets/* in the .gitignore and then write !secrets/*.txt to reinclude all the .txt files from the secrets folder to remove the folder from and reinclude all the .txt files in the folder from ignored files. 

Editing .gitignore file

Using git status –ignored to see whether the folder is removed from the ignored files or not

Now if our use case is to remove those files whose file_names are beginning with ! in the .gitignore file then add one more ! or add in the front of your file_name or you can also remove a folder by this who is having some files which don’t want git to have a track on them. By using these exceptions in the a.gitignore file you will move these files and folders in the ignored files.

Editing .gitignore

Using git status –ignored to see the files are in ignored files or not

A Global .gitignore file

So if our use case is that if we want specific files to be ignored by git in all repositories then we can create a global .gitignore in any of the repositories and make it global using the following command: 

git config --global core.excludesfile path_of_global_gitignore_file

Here you can see the path should be complete that is the name_of_the_drive/folder_name/.gitignore to avoid errors like this warning: unable to access permission denied fatal: cannot use as an exclude file. Now git will use this in addition to each repository’s .gitignore file. So let us see the syntax of the command:

Showing the syntax of the command: git config –global core.excludes file path_of_global_gitignore_file

So now if we edit the global .gitignore file and write *.py then it will ignore all the *.py files present in our repository. Now let’s see how this works:

Editing the global .gitignore file

So now if we use the git status –ignored command we will see all the .py files in ignored files. 

Using git status –ignored

So now if we include all these *.py files in the local .gitignore file of our repository then what will happen because our global .gitignore file ignores all the .py files. Now the question here is who will take the priority so the answer to this is our local .gitignore file takes priority always whenever there is a file that is ignored by the global .gitignore file but is included by the local .gitignore file. So we will write !*.py in our local. .gitignore file will include all the files .py files and will not put them in ignored files.

Editing the local .gitignore file

So, now we can see all the py files are now in untracked files and there are no py files that are in ignored files.

Using git status –ignored command to see whether the py files are removed from the ignored  files or not

Ignore all the files that already have been committed to a Git repository

So now if we want a file that already has been committed to the git repository and now we want that git should stop tracking it for that type of use-case we can remove it using the following command:

git rm --cached file

This will remove the file from the repository and prevent any further changes from being tracked by Git. The –cached option will make sure that the file is not physically deleted. The previously added contents of this file will still be visible but keep in mind that if anyone else pulls from the repository after the file is being removed then their copy will be physically deleted. 

Before using git rm –cached status of the file

After Using git rm –cached file  

You can make git pretend that the working tree version of the file is up to date thus ignoring changes in it with the skip-worktree option using the command.

git update-index --skip-worktree file_name

Here we can see that readme.md is modified

Here we can see that after using the above command git is ignoring any changes being done in the readme.md

Here we can see by using this above command git is not able to track any further changes in the readme.md and ignore any changes being done in the readme.md. Now to have a track of the changes in the readme.md we can use the command git update-index –no-skip-worktree file_name.

Using the command git update-index –no-skip-worktree file_name

Now we can see that on using git status we can see that readme.md is being modified and some changes need to be staged for commit. Now if you want to force git to ignore any changes made in a  file then we can use the command.

git update-index --assume-unchanged file_name 

Using the above command so that git doesn’t ignore the file

Now if we want that git shouldn’t ignore the file and again take care of it. For this, we will use the command 

git update-index --no-assume-unchanged file_name 

Using the above command so that git doesn’t ignore the file

Ignoring files locally without committing ignore rules

If you want to ignore certain files in a repository locally and not make the file part of any repository, then we will edit the .git/info/exclude inside your repository. Here we will ignore a file say rock.py and now we can see that before editing the file .git/info/exclude git is showing us the file in untracked files.

Before editing the file .git/info/exclude

Editing the file .git/info/exclude

Using git status –ignored to see the status of rock.py

Now we can see that rock.py is in ignored files now.
 

Ignoring a file in any directory 

If we want to ignore a file in any directory we have to just write its name in the  .gitignore file whether in your global or local or it can be your .git/info/exclude of the repository according to your use case. If you want that in your particular repo only a particular file in a specific directory should be ignored then you can mention the name of that file in the local.gitignore file and if you want that all the repositories should ignore the file then you can write the name of that file in global .gitignore then the file would be ignored by all the repositories.

Mentioning the name of the file .gitignore

Using git status –ignored

Here you can see the file is now in ignored files and whatever the folders were containing that file is also ignored. Now if you want to ignore a certain file in a specific folder only then we can edit the .gitignore just like this: mainfolder_name/**/file_name. Here ** denotes subdirectories. The meaning of mainfolder_name/**/file_name this line is only the file contained in this folder or its subdirectories will be ignored. But if the file is at some other location of the repository with the same name then that will not be ignored.

Editing the .gitignore

Using git status –ignored

Now we can see that the cars.cpp file created in the main folder is in the untracked files and the file cars.cpp which is present in the testing folder and its subdirectories are ignored because in the .gitignore file it is written that testing/**/cars.cpp which means all the files with cars.cpp name should be ignored in the testing folder and its subdirectories or what we can do is create a local .gitignore file in the folder where want to ignore the file. Now what are we doing is creating a local .gitignore file in the folder where we are going to ignore the file. So what we have done is we have erased this line testing/**/cars.cpp from our local .gitignore file so that we can see the effect of the .gitignore file present in our folder testing which we have newly created.

Editing the local  .gitignore

Using git status –ignored command

Now you can see that on using git status –ignored command we are seeing that cars.cpp from the testing folder and its subdirectories are ignored. 

Prefilled .gitignore Templates

Create an Empty folder

It is not possible to add and commit an empty folder in the git so to achieve this we have two methods:

Method one: .gitkeep  

So for tracking an empty folder in git we will create an empty folder inside the repository and in that folder create an empty .gitkeep file which will register the folder to git and we will be able to track the empty folder.

Checking the status of empty folder gitisfun without a .gitkeep

So now we can see that the gitisfun folder is not having any .gitkeep file and without any .gitkeep file it is not being tracked by git.  So let’s create a .gitkeep file in an empty folder so that we can track an empty folder in git.

Creating .gitkeep file in the empty folder

Adding the empty folder in the staging area

So now we can see that the empty folder is now being tracked by git. There is one more method by which we can track the empty folder in git.

Method two: dummy.txt

So to track an empty folder in git using dummy.txt, we will create an empty folder in which we will create a dummy.txt file, and in that, you can insert any funny messages you want and now after creating this dummy.txt file in the empty folder we will be able to add the empty folder in the staging area.

Without dummy.txt the empty folder is not being tracked by git

Created dummy.txt in the empty folder and now we can see that the empty folder is now being tracked by git 

Here the name of the empty folder is batman. So these are the two methods by which we can track an empty folder in git. 

Finding files ignored by .gitignore

So now if you want to see all the files ignored by git in your repository or any of the directories present in the repository we can use the following command:

git status --ignored

Using git status –ignored command

So now if you want to list recursively ignored files in directories, we will be using an additional parameter  –untracked-files=all, and the command would be:

git status --ignored --untracked-files=all

Using git status –ignored –untracked-files=all

So now we can see that it is listing all the recursively ignored files in directories also.

Ignoring changes in tracked files

So now if you are thinking of ignoring changes in tracked files then you might think that why not to use .gitignore or .git/info/exclude and just mention the name of the file which we want to ignore but .gitignore and .git/info/exclude only works for ignoring untracked files. So to ignore a tracked file we use the following command git update-index –skip-worktree file_name. So here you can see that the file try.txt which is in tracked files is modified but now after applying the command: git update-index –skip-worktree file_name any changes done in the try.txt is being ignored by the git because of the command we used.

Modifying the file try.txt

Using the command git update-index –skip-worktree file_name

So now we can see that after applying the command git update-index –skip-worktree file_name the tracked file is being ignored and now if you want to revert this we can use the following command: git update-index –no-skip-worktree file_name so this command will again make the file to be tracked by git.

Using the command git update-index –no-skip-worktree file_name

We can also use the command git update-index –assume-unchanged file_name in alternative to git update-index –skip-worktree file_name both works the same and in alternative to the command git update-index –no-skip-worktree we can use git update-index –no-assume-unchanged file_name command.

Понравилась статья? Поделить с друзьями:
  • Как написать get запрос
  • Как написать gamemode 1
  • Как написать gabe newell
  • Как написать g код вручную для чпу
  • Как написать future bass