What is the purpose of the .gitignore file?

GitLinuxOpen SourceSoftware & Coding

When a Git project is compiled it may generate binary files, lock files, temporary files and metadata files. These are intermediate files that are not part of the source code. For example, IDE config files or intermediate files like “.class”,”.exe”, “.bin” etc. that are generated during compilation should be ignored by the version control system as they will be different for each developer machine and will unnecessarily increase the size of the repository.

The .gitignore is a text file where each line contains a pattern for files or directories to ignore. It is usually placed at the root of the project folder. Alternatively, you can put it in any folder in the repository and a project can have multiple .gitignore files.

This file lists files that are intentionally untracked and should be ignored by Git. It is important to note that changes to files that were staged before being added to the .gitignore file will continue to be tracked by Git. In other words, .gitignore will only ignore files in the working directory.

Let us understand this with an example.

Step 1 − Create a folder “meta” and add a file “xyz.bin” to it. Add some content to the file.

$ mkdir meta
$ echo hello > meta/xyz.bin

Step 2 − Execute the command git status.

$ git status

Git displays a message stating the “meta/” file is untracked which means that the changes are not staged.

Untracked files:
   (use “git add <file>...” to include in what will be committed)
   meta/
Nothing added to commit but untracked files present (use “git add” to track)

Step 3 − Now let us say, that changes to the “meta” folder should be ignored by Git. To achieve this we will have to create .gitignore file and add the “meta/” folder to the .gitignore file as shown below −

$ meta/>.gitignore // creates a .gitignore file and tells it that changes to meta folder should be ignored
$ code .gitignore //opens the file in the default editor (here, VS Code)

The output of the above commands is shown in the screenshot.

Now let us verify if changes that were initially made to the meta folder is still tracked by Git. Us the git status command.

$ git status

The screenshot below that the “meta/” folder is now being ignored by Git.

Step 4 − Stage and commit the .gitignore file.

$ git add .gitignore
$ git commit −m ‘add gitignore file’

The output of the above commands is shown in the screenshot.

[master (root−commit) 6bd9c93] add gitignore file
1 file changed, 1 insertion(+)
create mode 100644 .gitignore
raja
Published on 20-Feb-2021 13:06:22
Advertisements