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

от admin

Ignoring files

You can configure Git to ignore files you don’t want to check in to GitHub.

Configuring ignored files for a single repository

You can create a .gitignore file in your repository’s root directory to tell Git which files and directories to ignore when you make a commit. To share the ignore rules with other users who clone the repository, commit the .gitignore file in to your repository.

GitHub maintains an official list of recommended .gitignore files for many popular operating systems, environments, and languages in the github/gitignore public repository. You can also use gitignore.io to create a .gitignore file for your operating system, programming language, or IDE. For more information, see «github/gitignore» and the «gitignore.io» site.

Open Terminal Terminal Git Bash .

Navigate to the location of your Git repository.

Create a .gitignore file for your repository.

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.

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 Terminal Terminal Git Bash .
  2. Configure Git to use the exclude file

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 Terminal Terminal Git Bash .
  2. Navigate to the location of your Git repository.
  3. Using your favorite text editor, open the file .git/info/exclude.
    in the Git documentation in the Git documentation in the github/gitignore repository site

Help us make these docs great!

All GitHub docs are open source. See something that's wrong or unclear? Submit a pull request.

.gitignore

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 используются шаблоны подстановки. С помощью различных символов можно создавать собственные шаблоны.

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

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

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

Общие файлы .gitignore в вашем репозитории

Обычно правила игнорирования Git задаются в файле .gitignore в корневом каталоге репозитория. Тем не менее вы можете определить несколько файлов .gitignore в разных каталогах репозитория. Каждый шаблон из конкретного файла .gitignore проверяется относительно каталога, в котором содержится этот файл. Однако проще всего (и этот подход рекомендуется в качестве общего соглашения) определить один файл .gitignore в корневом каталоге. После регистрации файла .gitignore для него, как и для любого другого файла в репозитории, включается контроль версий, а после публикации с помощью команды push он становится доступен остальным участникам команды. В файл .gitignore , как правило, включаются только те шаблоны, которые будут полезны другим пользователям репозитория.

Персональные правила игнорирования в Git

В специальном файле, который находится в папке .git/info/exclude , можно определить персональные шаблоны игнорирования для конкретного репозитория. Этот файл не имеет контроля версий и не распространяется вместе с репозиторием, поэтому он хорошо подходит для указания шаблонов, которые будут полезны только вам. Например, если у вас есть пользовательские настройки для ведения журналов или специальные инструменты разработки, которые создают файлы в рабочем каталоге вашего репозитория, вы можете добавить их в .git/info/exclude , чтобы они случайно не попали в коммит в вашем репозитории.

Глобальные правила игнорирования в Git

Кроме того, для всех репозиториев в локальной системе можно определить глобальные шаблоны игнорирования Git, настроив параметр конфигурации Git core.excludesFile . Этот файл нужно создать самостоятельно. Если вы не знаете, куда поместить глобальный файл .gitignore , расположите его в домашнем каталоге (потом его будет легче найти). После создания этого файла необходимо настроить его местоположение с помощью команды git config :

Будьте внимательны при указании глобальных шаблонов игнорирования, поскольку для разных проектов актуальны различные типы файлов. Типичные кандидаты на глобальное игнорирование — это специальные файлы операционной системы (например, .DS_Store и thumbs.db ) или временные файлы, создаваемые некоторыми инструментами разработки.

Игнорирование ранее закоммиченного файла

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

Опустите опцию —cached , чтобы удалить файл как из репозитория, так и из локальной файловой системы.

Коммит игнорируемого файла

Можно принудительно сделать коммит игнорируемого файла в репозиторий с помощью команды git add с параметром -f (или —force ):

Этот способ хорош, если у вас задан общий шаблон (например, *.log ), но вы хотите сделать коммит определенного файла. Однако еще лучше в этом случае задать исключение из общего правила:

Этот подход более прозрачен и понятен, если вы работаете в команде.

Скрытие изменений в игнорируем файле

Команда git stash — это мощная функция системы Git, позволяющая временно отложить и отменить локальные изменения, а позже применить их повторно. По умолчанию команда git stash ожидаемо не обрабатывает игнорируемые файлы и создает отложенные изменения только для тех файлов, которые отслеживаются Git. Тем не менее вы можете вызвать команду git stash с параметром —all, чтобы создать отложенные изменения также для игнорируемых и неотслеживаемых файлов.

Отладка файлов .gitignore

Если шаблоны .gitignore сложны или разбиты на множество файлов .gitignore , бывает непросто отследить, почему игнорируется определенный файл. Используйте команду git check-ignore с параметром -v (или —verbose ), чтобы определить, какой шаблон приводит к игнорированию конкретного файла:

При желании команде git check-ignore можно передать несколько имен файлов, причем сами имена могут даже не соответствовать файлам, существующим в вашем репозитории.

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

Dionysia Lemonaki

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

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:

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:

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:

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

You could also write the above like so:

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 :

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:

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:

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:

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:

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:

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:

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:

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:

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:

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

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:

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

Conclusion

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

How to create a .gitignore file

I need to add some rules to my .gitignore file. However, I can’t find it in my project folder. Isn’t it created automatically by Xcode? If not, what command allows me to create one?

Peter Mortensen's user avatar

41 Answers 41

If you’re using Windows, it will not let you create a file without a filename in Windows Explorer. It will give you the error "You must type a file name" if you try to rename a text file as .gitignore

Enter image description here

To get around this, I used the following steps.

  1. Create the text file gitignore.txt
  2. Open it in a text editor and add your rules, then save and close
  3. Hold Shift , right click the folder you’re in, and then select Open command window here
  4. Then rename the file in the command line, with ren gitignore.txt .gitignore

Alternatively, HenningCash suggests in the comments:

You can get around this Windows Explorer error by appending a dot to the filename without an extension: .gitignore. . It will be automatically changed to .gitignore .

Peter Mortensen's user avatar

As simple as things can (sometimes) be: Just add the following into your preferred command-line interface (GNU Bash, Git Bash, etc.)

As War pointed out in the comments, touch works on Windows as well as long as you provide the full path. This might also explain why it does not work for some users on Windows: The touch command seems to not be in the $PATH on some Windows versions by default.

Note: The path might differ, depending on your setup and installation path.

Peter Mortensen's user avatar

kaiser's user avatar

The easiest way to create the .gitignore file in Windows Explorer is to create a new file named .gitignore. .

This will skip the validation of having a file extension, since it actually has an empty file extension.

Peter Mortensen's user avatar

The .gitignore file is not added to a repository by default. Use vi or your favorite text editor to create the .gitignore file then issue a git add .gitignore followed by git commit -m "message" .gitignore . The following commands will take care of it.

Peter Mortensen's user avatar

In Windows

  1. Open Notepad.
  2. Add the contents of your gitignore file.
  3. Click "Save as" and select "all files".
  4. Save as .gitignore

Easy peasy! No command line required!

macOS and Linux one-liner

An easy way to get a default Git ignore without messing about with create/copy/paste is to use the curl command from the terminal. First cd into your projects root directory and then run the command by replacing MY_API_NAME with your API name from one of the following two sources:

gitignore.io

You can find your API name by searching from the list here and clicking Generate.

GitHub

Alternatively, you can use the ones at GitHub. Find the filename for your API here.

Windows

Here are some similar alternatives for Windows.

But honestly setting that up looks like more trouble that it is worth. If I had Windows then I would just create an empty file called .gitignore in my project’s root folder and then copy and paste the default text from gitignore.io or GitHub.

Peter Mortensen's user avatar

On Windows, you can use cmd:

Or use Git Bash cmd:

This useful for a Linux and Mac system.

Peter Mortensen's user avatar

I want my contribution as well. This time, animated one 🙂

Oo.oO's user avatar

Using the Git Bash console.

  • Navigate to your project
  • Type "touch .gitignore"

The .gitignore file will be created for you.

Enter image description here

Peter Mortensen's user avatar

Roberto Rodriguez's user avatar

My contribution is aimed at those on a Mac, and it can be applied to not only those working on an iOS project (as implied by the question mentioning Xcode), but any type of project.

The easy way that I do it is to go into the terminal and run vim .gitignore and then add the files. Usually you can just copy what you need from one of the templates on GitHub at https://github.com/github/gitignore.

Step 1
While in your project, type the following command

Step 2
You now have your file open with Vim.

Enter image description here

Press i to insert text. You will see that the file is ready when you see the —INSERT— at the bottom.

Enter image description here

Step 3 (option 1)
For Objective-C projects, you can copy from https://raw.githubusercontent.com/github/gitignore/master/Objective-C.gitignore and paste it into your .gitignore file:

Enter image description here

Press Esc , type in :wq , and press Return . Which saves the file.

Step 3 (option 2)
Add whatever files apply to your project.

If you are not sure what to add, the best keywords to use in your search engine would be to include your project type and text editor. For example, if you use Sublime Text you would want to add

And if you are working with a Cordova project in Dreamweaver you would want to add

Читать:
Как открыть файл vbs

Похожие статьи