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

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

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

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

Nick Volynkin

29.9k18 золотых знаков110 серебряных знаков198 бронзовых знаков

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

Peter OlsonPeter Olson

9,4025 золотых знаков26 серебряных знаков52 бронзовых знака

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

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

    type nul > .gitignore
    

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

Peter OlsonPeter Olson

9,4025 золотых знаков26 серебряных знаков52 бронзовых знака

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

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

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

https://github.com/github/gitignore

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

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


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

touch .gitignore
echo '' > .gitignore

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

Nick VolynkinNick Volynkin

29.9k18 золотых знаков110 серебряных знаков198 бронзовых знаков

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

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

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

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

insolorinsolor

28.2k7 золотых знаков34 серебряных знака64 бронзовых знака

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

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

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

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

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

KeyJooKeyJoo

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

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

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

MarioMario

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

Всё ещё ищете ответ? Посмотрите другие вопросы с метками windows git файлы gitignore или задайте свой вопрос.

Last Updated :
21 Jun, 2024

The .gitignore file is a powerful tool in Git that allows you to specify which files and directories should be ignored by Git. This helps prevent unnecessary files, such as build artefacts and temporary files, from being tracked and cluttering your repository. In this article, we will explore how to create and configure a .gitignore file to keep your Git repository clean and organized.

Table of Content

  • Why Use a .gitignore File?
  • Approach 1: Creating a .gitignore File Manually
  • Approach 2: Using Templates
  • Configuring the .gitignore File
  • Example
  • Applying Changes

Why Use a .gitignore File?

Using a .gitignore file is crucial for several reasons:

  • Clean Repository: Keeps your repository free from unnecessary files that do not need to be version controlled.
  • Security: Prevents sensitive information, like API keys and configuration files, from being accidentally committed.
  • Efficiency: Reduces the size of your repository by excluding large files and directories that are not required for version control.

Approach 1: Creating a .gitignore File Manually

To create a .gitignore file manually, follow these steps:

Step 1: Open your terminal or command prompt: Navigate to the root directory of your Git repository.

Step 2: Create the .gitignore file: Use the following command to create the file

touch .gitignore

Open the .gitignore file: Use a text editor to open and edit the .gitignore file. For example, with nano:

nano .gitignore

Approach 2: Using Templates

There are various templates available for different programming languages and frameworks that you can use as a starting point. GitHub provides a collection of .gitignore templates at github.com/github/gitignore.

Steps to use a template:

  • Find the appropriate template: Go to the GitHub repository and find the .gitignore template that matches your project.
  • Copy the contents: Copy the content of the template.
  • Paste into your .gitignore file: Open your .gitignore file and paste the copied content.

Configuring the .gitignore File

The .gitignore file uses simple pattern matching to specify which files and directories should be ignored. Here are some basic patterns:

Ignoring Specific Files: To ignore specific files, simply list their names:

file.txt

Ignoring Specific Directories: To ignore entire directories, append a slash (/) to the directory name:

/node_modules/
/build/

Ignoring Files by Extension: To ignore all files with a specific extension, use a wildcard (*):

*.log
*.tmp

Ignoring Nested Files and Directories: To ignore files and directories at any level, prefix the pattern with two asterisks (**):

**/temp/
**/*.backup

Negating Patterns: To include a file that would otherwise be ignored by a previous pattern, prefix the pattern with an exclamation mark (!):

!important.log
!/keep/

Example

Here are some common examples of patterns used in a .gitignore file:

# Logs
logs
*.log

# Dependency directories
node_modules/

# Build output
dist/
build/

# Environment variables
.env

# IDE files
.vscode/
.idea/

Applying Changes

Once you have created and configured your .gitignore file, make sure to add and commit it to your repository:

git add .gitignore
git commit -m "Add .gitignore file"
git push origin <branch-name>

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

gitignore

Git работает по следующему принципу: вы размещаете файлы в проекте с помощью команды git add, а затем фиксируете (коммитите) их с помощью команды git commit.

При совместной работе над проектами могут возникнуть ситуации, когда вы не захотите, чтобы какие-то файлы или части проекта были видны всем участникам команды.

Иными словами, вы не захотите включать и фиксировать эти файлы в основной версии проекта. Вот почему вы можете не захотеть использовать разделитель (точку) с командой git add, так как в этом случае каждый отдельный файл будет размещен в текущем каталоге Git.

Когда вы используете команду git commit, то каждый отдельный файл фиксируется – это также добавляет файлы, которые не нужно.

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

Итак, как же сделать так, чтобы Git игнорировал и не отслеживал определенные файлы? С помощью файла .gitignore.

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


Что такое файл .gitignore? Для чего он нужен?

Каждый из файлов в любом текущем рабочем репозитории Git относится к одному из трех типов:

  • Отслеживаемые – это все файлы и каталоги, о которых знает Git. Это файлы и каталоги, которые были недавно размещены (добавлены с помощью git add) и зафиксированы (закоммичены с помощью git commit) в главном репозитории.
  • Неотслеживаемые – это новые файлы и каталоги, которые созданы в рабочем каталоге, но еще не размещены (или добавлены с помощью команды git add).
  • Игнорируемые – это все файлы и каталоги, которые полностью исключаются и игнорируются, и никто о них в репозитории Git не знает. По сути, это способ сообщить Git о том, какие неотслеживаемые файлы так и должны остаться неотслеживаемыми и не должны фиксироваться.

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

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

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


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

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

Тем не менее, вы можете поместить этот файл в любую папку в репозитории. Если на то пошло, но у вас может быть несколько файлов .gitignore.

Для того, чтобы создать файл .gitignore в Unix-подобной системе, такой как macOS или Linux, с помощью командной строки, откройте приложение терминала (например, в macOS это Terminal.app). Затем для того, чтобы создать файл .gitignore для вашего каталога, перейдите в корневую папку, которая содержит проект, и при помощи команды cd введите следующую команду:

touch .gitignore

Файлы, перед именем которых стоит точка ., по умолчанию скрыты.

Скрытые файлы нельзя просмотреть, используя только команду ls. для того, чтобы иметь возможность просмотреть все файлы, включая скрытые, используйте флаг -a с командой ls следующим образом:

ls –a

Что добавлять в файл .gitignore

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

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

Вот некоторые файлы, которые могут быть включены:

  • Файлы операционной системы. Каждая операционная система, будь то macOS, Windows или Linux, создает системные скрытые файлы, которые не нужны другим разработчикам, так как их система создает такие же файлы. Например, в macOS Finder создает файл .DS_Store, который содержит пользовательские настройки внешнего вида и отображения папок, такие как размер и положение иконок.
  • Файлы конфигурации, создаваемые такими приложениями, как редакторы кода и IDE (Integrated Development Environment – интегрированная среда разработки). Эти файлы настроены под вас, ваши конфигурации и ваши настройки, например папка .idea.
  • Файлы, которые автоматически генерируются языком программирования или средой разработки, которую вы используете для своего проекта, и в процессе компиляции специфичных для кода файлов, такие как файлы .o.
  • Папки, созданные диспетчерами пакетов, например, папка npm node_modules. Это папка, которая используется для сохранения и отслеживания зависимостей для каждого пакета, который вы устанавливаете локально.
  • Файлы, которые содержат конфиденциальные данные и личную информацию. Примерами таких файлов могут послужить файлы с вашими учетными данными (имя пользователя и пароль) и файлы с переменными среды, такие как файлы .env (файлы .env содержат ключи API, которые должны оставаться защищенными и закрытыми).
  • Файлы среды выполнения, такие как файлы .log. Они предоставляют информацию об использовании операционной системы и ошибках, а также историю событий, произошедших в рамках ОС.

Как игнорировать файл или папку в Git

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

Например, если вы хотите игнорировать файл text.txt, который расположен в корневом каталоге, то вы должны сделать следующее:

/text.txt

А если вы хотите игнорировать файл text.txt, который расположен в папке test корневого каталоге, вы должны сделать следующее:

/test/text.txt

Вы можете это записать иначе:

test/text.txt

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

Например, если вы хотите игнорировать любые файлы text.txt, то вы должны добавить в .gitignore следующее:

text.txt

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

Для того, чтобы игнорировать весь каталог со всем его содержимым, вам нужно указать имя каталога со слешем в конце:

test/

Эта команда позволит игнорировать любой каталог (включая другие файлы и другие подкаталоги внутри каталога) с именем test, расположенный в любой папке вашего проекта.

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

# соответствует любым файлам и каталогам с именем test
test       

Что делать, если вы хотите игнорировать любые файлы и каталоги, которые начинаются с определенного слова?

Допустим, вы хотите игнорировать все файлы и каталоги, имя которых начинается с img. Для этого вам необходимо указать имя, а затем селектор подстановочного символа *:

img*

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

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

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

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

*.md

Этот шаблон будет соответствовать любому файлу с расширением .md, расположенному в любой папке проекта.

Мы разобрали, как игнорировать все файлы, которые оканчиваются одинаково. Но что делать, если вы хотите сделать исключение для одного из этих файлов?

Допустим, вы добавили в свой файл .gitignore следующее:

.md

Этот шаблон позволит игнорировать все файлы, оканчивающиеся на .md, но вы, например, не хотите, чтобы Git игнорировал файл README.md.

Для этого вам нужно будет воспользоваться шаблоном с отрицанием (с восклицательным знаком), чтобы исключить файл, который в противном случае был бы проигнорирован, как и все остальные:

 # игнорирует все файлы .md
.md

# не игнорирует файл README.md
!README.md      

Учитывая эти два шаблона в файле .gitignore, все файлы, оканчивающиеся на .md будут игнорироваться, кроме файла README.md.

Стоит отметить, что данный шаблон не будет работать, если вы игнорируете весь каталог.

Допустим, что вы игнорируете все каталоги test:

test/

И допустим, внутри папки test у вас есть файл example.md, который вы не хотите игнорировать.

В этом случае вы не сможете сделать исключение для файла внутри игнорируемого каталога следующим образом:

# игнорировать все каталоги с именем test
test/

# попытка отрицания файла внутри игнорируемого каталога не сработает
!test/example.md

Как игнорировать ранее закоммиченый файл

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

Git может игнорировать только неотслеживаемые файлы, которые еще не были зафиксированы в репозитории.

Что же делать, если вы уже закоммитили файл, но хотели бы, чтобы он все-таки не был закоммичен?

Допустим, что вы случайно закоммитили файл .env, в котором хранятся переменные среды.

Для начала вам необходимо обновить файл .gitignore, чтобы включить файл .env:

# добавить файл .env в .gitignore
echo ".env" >> .gitignore       

Теперь, вам нужно указать Git не отслеживать этот файл, удалив его из перечня:

git rm --cached .env

Команда git rm вместе с параметром --cached удаляет файл из репозитория, но не фактический файл. Это значит, что файл остается в вашей локальной системе и в вашем рабочем каталоге в качестве файла, который игнорируется.

Команда git status покажет, что файла в репозитории больше нет, в ввод команды ls покажет, что файл существует в вашей локальной файловой системе.

Если вы хотите удалить файл из репозитория и вашей локальной системы, то не используйте параметр --cached.

Затем добавьте .gitignore в область подготовленных файлов с помощью команды git add:

git add .gitignore

И наконец, закоммитте файл .gitignore с помощью команды git commit:

git commit -m "update ignored files"

Заключение

Вот и все – теперь вы знаете, как игнорировать файлы и папки в Git.

A Version Control System (VCS) is a software commonly used to track changes to a project and allow easy collaboration. Git is one of the most common version control systems out there. Git can be used to track changes to individual files in a project, roll-back accidental changes, and, guess what? bring back accidentally deleted project files in some cases.

Git can also help you merge the changes made by different collaborators on the same file and much more. Isn’t that cool? By default, Git tracks changes across all files where it is initialized. When Git is installed on your computer, you can easily start tracking any folder using simple commands. A folder that is being tracked using Git is called a git repository or git repo, in short.

git init 
Initialize the git repository
git add .
Start tracking all files
git commit "minor changes"
Commit your changes

These are a few simple git commands to give you an idea of how easy it is to use Git. You can find many examples online, so you can simply start using Git and learn the commands along the way.

The .gitignore file

Ignoring the files means telling Git not to track changes to them. That also means you cannot roll back accidental changes made to that file. The file is mostly used to avoid committing transient (short-lived) files from your working directory that aren’t useful to other collaborators, such as compile-time logs, build folders and outputs, temporary files IDEs create, etc.

To tell Git not to track some files, we put a file called .gitignore in the folder that is being tracked by Git. The .gitignore file tells Git which files or folders it should ignore.  A file named .gitignore usually resides in the project’s root folder. Here is a simple project that is being tracked by Git. Notice the first folder named .git? Git creates that folder for keeping track of the changes in the files in this project. Also, notice the file at the last? That’s the .gitignore file right there!

There is a hidden file named .gitignore in the project folder.

How to create a .gitignore file

Some tools & IDEs will generate a .gitignore file automatically when you start a new project. If you have cloned a project from an existing remote repository, it probably has a .gitignore file already. If you don’t see a file named .gitignore, you can create a new .gitignore file yourself. Either you can use a text editor, or any command or trick you know to create a new file and name it .gitignore. It’s that simple. From the terminal, you can do touch .gitignore or from your File Manager, right click and select the Create New File or similar command. Or you can create a new document in a text editor and save the empty file while giving it the name .gitignore.

Example of a .gitignore file

GitHub maintains a repository of .gitignore files for almost all languages and frameworks. You can look for the one that you need from the following URL https://github.com/github/gitignore. Download the appropriate file and copy it to your project’s root folder, then rename it to .gitignore by removing the filename. Even if you already have a .gitignore file in your project’s root folder you can look at the contents of the file there, and make necessary changes in your own .gitignore file. This is what a gitignore file looks like. The lines starting with a # are comments that are optional. I prefer keeping a comment so I know why I ignored that particular file at that time.

Example of a .gitignore file

When to create a .gitignore file

Ideally, you should create a .gitgnore file as soon as you start your project, even if it is empty. It’s best to initiate a git repository after creating the .gitignore file. That helps git identify the files that do not need to be tracked. If you add a .gitignore file in the git repository where the files are already tracked, you need to manually remove and un-track the already tracked files. That’s why it is a good idea to make the .gitignore file one of the first ones in the git repository. If you need to ignore a file that is already being tracked, you need to do that individually using the following command:

$ git rm --cached PATH_TO_FILE

Personally, I prefer to add a .gitignore file and a README.md file as soon as I create a new project.

Why create a .gitignore file

This is one of the most common questions that a beginner asks. Why should you ignore some files in the repository instead of checking them all into Git? That’s because not all files in your working directory are useful or relevant to you or other collaborators. Some files can even contain information that you’d like to store temporarily. When you check-in a file to git, all the changes to it are stored in git, which might not be necessary. If you are not sure whether you should keep a file/folder or ignore it, the following examples will give you an idea.

1. Ignore Large Files

We usually don’t add large files to the VCS to limit the size of our repositories. To do that, as soon as the new files or folders are added, we add them to the .gitignore file. Even if you accidentally added and then later deleted the file, the size of the repository will always be way larger than it should have been. When you check in large, unnecessary files, it takes much more bandwidth and storage than is necessary. Unless the files are extremely important for the project to run and cannot be shared by other mediums like local lan-share or uploaded to a common cloud drive, such files should be ignored.

2. Ignore libraries, archives, build outputs, etc.

Sometimes you might have downloaded a collection of assets, or an entire library or datasets to work on the project. Instead of tracking the file on the VCS, add a message on the README file about how and where to find those extra files. Most modern build tools let you define the requirements in files like package.json, composer.json or requirements.txt, etc. Such libraries are stored in separate folders like node_modules or vendors or packages. In this case, the libraries can be re-downloaded from the Internet whenever someone else clones the repository. Adding the third-party libraries into your git repository, and tracking changes to all of them is unnecessary.

3. Ignore temporary files

It’s a good practice to have a folder named tmp on your project root, and ignore it by adding a new line, tmp/, in the .gitignore file. You might as well add large and non-essential files to this directory because they will not be checked into the VCS. Other examples of temporary files include temporary databases, or temporary folders mounted as docker volumes during local development. Personally, I create a folder named «tmp» in all of my projects and ask git to ignore it. Then I don’t have to worry about accidentally adding unnecessary files because everything temporary goes inside that folder.

3. Local and Environment-specific files

Your development environment might not match your staging or production environment. The settings of your IDE, your local database credentials, paths to your local libraries, and your SDK path might not match that of your coworkers. In that case, whenever your changes are pulled by other members of the project, the project might not build because of mismatched configuration & missing files. That’s why people keep such configuration in a single file and ignore it using the .gitignore file. One example of such files is local.properties in an Android app project that includes the local Android SDK installation path, which looks like «sdk.dir=/Users/nj/Library/Android/sdk» on my computer. If I forgot to ignore the file and someone else clones the repository, the IDE cannot find the build tools in that folder. They need to change the file location to something else. When they push their changes back, I need to change the file again to make it work. This doesn’t look like a great idea, does it? If we ignore the file altogether, both of us can have a local copy of the local.properties file in our working directory and not worry about overriding each other’s settings.

Another common example is a file named .env which contains the environment variables for the project. Environment Variables – The name tells us that the variables will differ in different environments. Since that particular file may also contain confidential information, I’m breaking it down into separate bullet points below.

4. Credentials, Secrets and Environment Variables

If your project depends on third-party services you might need your secrets and credentials in order to make use of such services. Also, you need different types of settings when you’re running a project in a production server, staging server or your local development machine. You definitely don’t want your production database password to be available to everyone in the organization or the public. That’s why all confidential information is usually stored in a file, which is not shared between the environments. An example of such a file is the .env file in a web-based project that includes your credentials of a database server, API keys, and other secrets. Each environment (local, development, staging and production) has a different copy of the file.

An example of my .env file

The above file looks completely different in the production server, where the password might be longer, the database host might not be localhost, and the AWS key and secret would definitely be longer.

You should NEVER add the files containing secrets or confidential information like passwords and secret keys to git. That’s because the credentials and API keys and secret should be transmitted over a secured channel like SSH or using vault. Most developers add a file called env.example alongside the .env file and only add the keys, omitting the values make it easy for the collaborators.

Things to remember about the .gitignore file

  • The .gitignore file itself should be checked into the VCS along with the other files, which means you should not add the line /.gitignore in the .gitignore file.
  • If you had accidentally ignored the .gitignore file itself, delete that line, then run the command git add .gitignore to start tracking the file again.
  • Closely monitor the changes to the .gitignore file to ensure no files that need to be tracked are accidentally added to it.
  • As the .gitignore file is a hidden file, it sometimes gets lost when you copy-paste the project contents to a different folder. Sometimes the entire .git folder is lost too, so take special care while copying contents from a local repository.

Common Problems

While telling Git to not track a file seems trivial, most beginners run into at least a problem while creating and using a .gitignore file. Here are some of the common problems that I have found.

1. The .gitignore file is not visible (hidden by filesystem)

The .gitignore file might not be visible on your file manager (My Files, My Computer, Finder, Folder, whatever it is called) because it is a file with only an extension; it doesn’t actually have a filename. Since the filename itself starts with a dot (full stop, or period), your operating system considers it a «hidden» file.  You need to enable showing hidden and system files appropriately to be able to see the file.

Terminal window

To show the hidden .gitignore file in the current folder, type ls -a and hit enter.

Linux Desktop

Open the «Files» or «F application, navigate to the folder and type Ctrl + H (hold the Ctrl key and press H once) to show hidden files.

Mac OS

Open the «Finder» application, navigate to the folder and type command + shift + . (hold the Command key, hold the Shift key, and press the full-stop or period key)  to show hidden files.

Windows PC

On Windows,  follow these steps to show the hidden .gitignore file:

  1. Open the File Explorer app
  2. From the View menu, select the Folder & Search Options option
  3. Switch to the Folder Options tab
  4. Check the Show Hidden Files option
  5. Uncheck the Hide Operating System Files option (optional)
  6. Close the Folder & Search Options window
  7. All the hidden files will be visible

Thanks for reading. Subscribe using either of the buttons below for more!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Genius ilook 111 windows 10
  • Sql server 2014 windows server 2019
  • Windows 24 hour clock
  • Как выключить фаерволы windows 10
  • Sony xperia windows mobile