Как создать файл gitignore windows 10

Когда пытаюсь создать файл .gitignore в Windows, приводит к ошибке:

You must type a file name

Как можно создать файл .gitignore?

Nick Volynkin's user avatar

Nick Volynkin

33.8k25 золотых знаков130 серебряных знаков222 бронзовых знака

задан 28 июл 2015 в 8:13

Peter Olson's user avatar

Peter OlsonPeter Olson

10.4k7 золотых знаков30 серебряных знаков53 бронзовых знака

2

  • Можно создать файл .gitignore., с точкой в конце. Точка в конце исчезает автоматическим образом.

  • Тоже возможно создать файл используя cmd.exe:

    type nul > .gitignore
    

ответ дан 28 июл 2015 в 8:21

Peter Olson's user avatar

Peter OlsonPeter Olson

10.4k7 золотых знаков30 серебряных знаков53 бронзовых знака

7

  1. Создай файл gitignore.txt
  2. Отредактируй в текстовом редакторе по вкусу
  3. Далее шифт + правый клик мышкой внутри папки, где лежит файл
  4. Выбираешь «Open command window here» или как это там по-русски
  5. Запустится cmd.exe уже в этой папке. Пишешь ren gitignore.txt .gitignore, файл переименовывается.

ответ дан 28 июл 2015 в 8:20

Sergey Snegirev's user avatar

2

Можно скачать готовый .gitignore с GitHub. Там есть специальный репозиторий, в котором сохраняются шаблоны .gitignore для разных языков и фреймворков.

https://github.com/github/gitignore

Разумеется, потом его можно отредактировать, хоть вовсе оставить пустым.

Сам GitHub использует этот репозиторий, когда предлагает добавить .gitignore во вновь создаваемый репозиторий. Поэтому ссылка почти наверняка не сломается.


Из git bash или cygwin работают следующие способы:

touch .gitignore
echo '' > .gitignore

ответ дан 28 июл 2015 в 9:08

Nick Volynkin's user avatar

Nick VolynkinNick Volynkin

33.8k25 золотых знаков130 серебряных знаков222 бронзовых знака

4

Ну раз Total Commander, то так:

  • заходим в нужную папку
  • жмем Shift-F4, вписываем имя файла как есть .gitignore, жмем Enter
  • открывается редактор, указанный в настройках Total Commander (какой-нибудь легковесный редактор с подсветкой синтаксиса, например)
  • прописываем содержимое, жмем сохранить

Собственно, все. Никаких манипуляций с именем файла не нужно.

ответ дан 21 фев 2017 в 17:04

insolor's user avatar

insolorinsolor

47.2k17 золотых знаков56 серебряных знаков99 бронзовых знаков

Total Commander и все операции с папками и файлами

Всякие разные операции с файлами классно проделываю в Windows 98 — Windows 10 в любимом редакторе: Total Commander

  • [x] Создать .gitignore.txt
  • [x] Двойной клик по имени файла
  • [x] Удалить выделенное .txt
  • [x] Подтверждаю нажатием

P.s. — Всегда проверяем кодировку файла: UTF-8

Дух сообщества's user avatar

ответ дан 21 фев 2017 в 16:14

vovs03's user avatar

vovs03vovs03

1002 серебряных знака11 бронзовых знаков

7

Есть простой вариант, создайте обычный текстовый фаил .txt, не важно как будет называться, затем откройте его, перейдите в раздел сохранить как, далее впишите имя фаила .gitignore, далее, ниже в разделе «тип фаила» выбирите все фаилы . и все, переименуется

ответ дан 2 авг 2017 в 6:28

Mario's user avatar

MarioMario

10010 бронзовых знаков

Вы можете настроить Git для игнорирования файлов, которые вы не хотите возвращать в GitHub.

Настройка игнорируемых файлов для одного репозитория

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

GitHub поддерживает официальный список рекомендуемых .gitignore файлов для многих популярных операционных систем, сред и языков в общедоступном репозитории github/gitignore. Вы также можете использовать gitignore.io для создания .gitignore файла для операционной системы, языка программирования или интегрированной среды разработки. Дополнительные сведения см. в разделе github/gitignore и на сайте gitignore.io.

  1. Откройте ТерминалТерминалGIT Bash.

  2. Перейдите к расположению репозитория Git.

  3. .gitignore Создайте файл для репозитория.

    touch .gitignore
    

    Если команда будет выполнена успешно, она не выведет никаких данных.

Пример .gitignore файла см. в разделе «Некоторые распространенные конфигурации gitignore» в репозитории Octocat.

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

git rm --cached FILENAME

Настройка игнорируемых файлов для всех репозиториев на компьютере

Вы можете сообщить Git всегда игнорировать определенные файлы или каталоги при создании фиксации в любом репозитории Git на компьютере. Например, эту функцию можно использовать для пропуска любых временных файлов резервного копирования, создаваемых текстовым редактором.

Чтобы всегда игнорировать определенный файл или каталог, добавьте его в файл с именем ignore , расположенным внутри каталога ~/.config/git. По умолчанию Git будет игнорировать все файлы и каталоги, перечисленные в глобальном файле ~/.config/git/ignoreконфигурации. git Если каталог и ignore файл еще не существуют, их может потребоваться создать.

Исключение локальных файлов без создания файла .gitignore

Если вы не хотите создать файл для совместного .gitignore использования с другими пользователями, можно создать правила, которые не зафиксированы в репозитории. Этот метод можно использовать для локально создаваемых файлов, которые не должны создавать другие пользователи, например, для файлов, создаваемых редактором.

Используйте любимый текстовый редактор, чтобы открыть файл, вызываемый .git/info/exclude в корневом каталоге репозитория Git. Любое добавляемое здесь правило не будет синхронизироваться, и будут игнорироваться только файлы для локального репозитория.

  1. Откройте ТерминалТерминалGIT Bash.
  2. Перейдите к расположению репозитория Git.
  3. Откройте файл .git/info/excludeс помощью избранного текстового редактора.

Дополнительные материалы

  • Игнорировать файлы в документации по Git
  • .gitignore в документации по Git
  • Коллекция полезных шаблонов .gitignore в репозитории github/gitignore
  • Сайт gitignore.io

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

В данном руководстве мы рассмотрим, как создать файл gitignore в операционной системе Windows 10. Опишем несколько способов, которые помогут вам начать использовать этот инструмент эффективно и без лишних сложностей.

Первый способ — создание файла gitignore вручную. Для этого вам потребуется открыть текстовый редактор (например, Блокнот) и создать новый файл с названием «.gitignore» (обратите внимание на точку в начале названия файла). В этом файле каждая новая строка представляет собой шаблон для игнорирования определенных файлов или папок.

Если у вас уже есть определенные файлы или папки, которые хотите игнорировать, вы можете просто добавить их шаблоны в файл gitignore. Например, для игнорирования всех файлов с расширением .log вы можете добавить следующую строку: «*.log».

Содержание

  1. Установка и настройка Git Bash
  2. Создание нового репозитория на GitHub
  3. Создание файла gitignore
  4. Редактирование файла gitignore
  5. Использование файла gitignore

Установка и настройка Git Bash

  1. Перейдите на официальный сайт Git (https://git-scm.com/) и скачайте установщик Git для Windows.
  2. Запустите установщик и следуйте инструкциям. Выберите путь установки (рекомендуется оставить значение по умолчанию).
  3. На этапе «Выберите компоненты» убедитесь, что опция «Git Bash here» выбрана. Она добавит контекстное меню в проводнике Windows, позволяя запускать Git Bash из любого каталога.
  4. На этапе «Настройка оконного терминала» выберите «Use Git from Git Bash only».
  5. На этапе «Настройка конвертеров текстовых файлов» выберите «Checkout Windows-style, commit Unix-style line endings».
  6. Настройте наименование репозитория и указывающий ваше имя пользователя и электронную почту.
  7. После завершения установки запустите Git Bash из меню «Пуск» или кликнув правой кнопкой мыши на нужной папке и выбрав «Git Bash here».
  8. Попробуйте ввести команду «git —version» в командной строке Git Bash. Если вы увидели версию Git, значит установка прошла успешно.

После установки и настройки Git Bash вы будете готовы использовать все функции Git для работы с репозиториями и управления версиями вашего кода.

Создание нового репозитория на GitHub

Чтобы создать новый репозиторий на GitHub, следуйте приведенным ниже шагам:

  1. Откройте ваш браузер и перейдите на официальный сайт GitHub.
  2. Если у вас еще нет аккаунта на GitHub, создайте его, заполнив необходимую информацию.
  3. После входа в свою учетную запись нажмите на кнопку «New» (Новый) в правом верхнем углу экрана.
  4. На странице создания нового репозитория введите название репозитория в поле «Repository Name» (Имя репозитория).
  5. По желанию вы можете также добавить краткое описание репозитория в поле «Description» (Описание), а также выбрать его видимость (публичный или приватный).
  6. Выберите опцию «Initialize this repository with a README» (Инициализировать данный репозиторий с README файлом), чтобы создать новый README.md файл в репозитории.
  7. Если вы хотите, чтобы ваш репозиторий был доступен только для сотрудников или конкретных пользователей, вы можете добавить их в список «Collaborators» (Соавторы).
  8. Нажмите на кнопку «Create repository» (Создать репозиторий), чтобы завершить процесс создания.

В течение нескольких секунд новый репозиторий будет создан, и вы будете перенаправлены на его страницу. Теперь вы можете начать работу с вашим новым репозиторием на GitHub.

Создание файла gitignore

Для создания файла gitignore в операционной системе Windows 10 необходимо выполнить следующие шаги:

  1. Откройте проводник Windows и перейдите в папку, в которой находится локальный репозиторий Git, для которого вы хотите создать файл gitignore.
  2. Создайте новый текстовый файл. Для этого можно использовать любой текстовый редактор, такой как Notepad, Notepad++ или другие.
  3. Переименуйте новый файл в «.gitignore» (без кавычек), удалив расширение «.txt» (если оно было добавлено автоматически).
  4. Откройте файл «.gitignore» в выбранном текстовом редакторе.
  5. Внесите нужные изменения в файл gitignore, добавив имена файлов, каталогов и шаблонов, которые вы хотите проигнорировать в репозитории Git. Каждый элемент добавляется в новой строке.
  6. Сохраните файл gitignore.

После создания и сохранения файла gitignore Git будет игнорировать указанные файлы и каталоги при выполнении команд Git, таких как git add, git commit и других. Это позволяет избежать случайного добавления чувствительных данных в репозиторий или сохранение ненужных файлов.

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

Редактирование файла gitignore

Для редактирования файла .gitignore на Windows 10 вы можете использовать любой текстовый редактор, такой как Notepad, Sublime Text или Visual Studio Code. Важно выбрать редактор, который позволяет сохранять файлы в кодировке UTF-8 без BOM, так как это рекомендуемая кодировка для файлов Git.

Чтобы создать новый файл .gitignore, вы можете открыть пустой текстовый документ в выбранном редакторе. Затем сохраните его с именем «.gitignore» (без кавычек) и убедитесь, что сохраняете его как обычный текстовый файл с расширением .gitignore.

Один из примеров содержимого файла .gitignore может выглядеть следующим образом:


# Игнорировать файлы с расширением .log
*.log
# Игнорировать директорию temp/
temp/
# Игнорировать конкретный файл example.txt
example.txt

В данном примере файлы с расширением .log, директория temp/ и конкретный файл example.txt будут проигнорированы Git при выполнении команды git add или git commit.

После создания или редактирования файла .gitignore сохраните изменения и убедитесь, что файл находится в корневой директории вашего репозитория. Git будет автоматически использовать этот файл для игнорирования соответствующих файлов и директорий.

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

Использование файла gitignore

Использование файла gitignore является хорошей практикой при работе с Git, особенно если вы работаете в команде или ваш проект включает в себя большое количество файлов. Файл gitignore позволяет избежать случайного добавления нежелательных файлов в репозиторий, что может снизить эффективность работы с Git и увеличить объем репозитория.

Файл gitignore может содержать простые шаблоны и расширенные шаблоны для определения набора правил игнорирования файлов. Простые шаблоны могут быть использованы для игнорирования файлов с определенным расширением или по имени файла. Расширенные шаблоны позволяют указать более сложные правила, такие как игнорирование файлов в определенной директории или игнорирование файлов, соответствующих определенным условиям.

Файл gitignore должен располагаться в корневой папке репозитория и называться .gitignore. Каждая строка в файле gitignore представляет собой шаблон для игнорирования определенных файлов или директорий. Комментарии могут быть добавлены, начиная с символа #. Используйте специальные символы, такие как *, для указания шаблонов с общими условиями игнорирования файлов. Например, *.tmp игнорирует все файлы с расширением .tmp, а /build игнорирует директорию build в корневой папке репозитория.

В таблице ниже показаны некоторые примеры шаблонов для использования в файле gitignore:

Шаблон Описание
*.log Игнорировать все файлы с расширением .log
temp/ Игнорировать директорию temp в корневой папке репозитория
!/src/main.cpp Не игнорировать файл main.cpp в директории src
/*.txt Игнорировать все файлы с расширением .txt в корневой папке репозитория

После создания или изменения файла gitignore, необходимо выполнить команду git add .gitignore и git commit -m «Add .gitignore» для добавления файла gitignore в репозиторий. В дальнейшем Git будет автоматически игнорировать файлы, указанные в файле gitignore при добавлении их в репозиторий.

If you have a project that you have git enabled, but you don’t want git to track all of the files in the project folder (perhaps because you don’t want all files to be uploaded to github), you can tell Git to ignore certain files, file types, or sub-directories by creating a “.gitignore” file in your git repository.

To set up a .gitignore file on a Windows machine, in your command window cd to the git directory and type the command:

run dir > .gitignore

This outputs the entire directory listing to a file named .gitignore in your git directory.

To edit the .gitignore file, open it in Notepad++ and replace the directory listing with a single line that contains the file types you want git to ignore. For example, if you want git to ignore .pyc files:

*.pyc

When you run the git status command in your project folder, Git will read every line of the .gitignore file, where each line is a condition that git should ignore. The types of conditions that can be set in the .gitignore file are:

  • File types
  • individual file names
  • specific directories

Here is a table that shows how to implement each of these condition types:

File types *.pyc
individual file names thisfile.txt
specific directories directory_name/

Notes:

  • Notice that * can used as a wildcard (meaning anytime this pattern is found).
  • Also note that for specific directories, all that is needed is to append the directory name with a forward slash.
  • Pound signs ‘#’ can be used as comment lines

Here is an example of a real .gitignore file:

# .gitignore for Grails 1.2 and 1.3
# Although this should work for most versions of grails, it is
# suggested that you use the "grails integrate-with --git" command
# to generate your .gitignore file.

# web application files
/web-app/WEB-INF/classes

# default HSQL database files for production mode
/prodDb.*

# general HSQL database files
*Db.properties
*Db.script

# logs
/stacktrace.log
/test/reports
/logs

# project release file
/*.war

# plugin release files
/*.zip
/plugin.xml

# older plugin install locations
/plugins
/web-app/plugins

# "temporary" build files
/target

There are many other real .gitignore files that can be used as examples here:
https://github.com/github/gitignore

For more information about gitignore, see:
https://help.github.com/articles/ignoring-files/
https://git-scm.com/docs/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 to remove the file from the index. The filename
can then be added to the .gitignore file to stop the file from
being reintroduced in later commits.

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

  • Как создать файл cmd на windows 10
  • Как создать файл cfg на windows 10 через блокнот
  • Как создать файл bin в windows 10
  • Как создать установочный носитель для windows
  • Как создать установочную флешку windows 11 rufus