8 Ignore Files

8.1 Use .gitignore Files

  • git recognizes when new files are added to the directory or files are changed.

  • but what if we don’t want to track some files? how do we ignore some changes?

  • use a project/.gitignore

    • list of rules to determine which files to ignore

  • pattern matching (regular expressions)

    • `*?[aeiou][0-9]

    • example: `logs/*.txt

    • negative expressions: *.php !index.php. Ignore all php but do not ignore index.php

  • ignore all files in a direction with trailing slash. Example: assets/videos/

  • comments with #. Example: # This is a comment.

  • Blank lines are skipped

  • Recall, git commit -am only adds tracked changes.

8.2 Ideas on what to ignore

  • depends on what kind of project you have.

  • ignore compiled source code

  • packages and compressed files

  • logs and databases (changing frequently)

  • OS generated files

  • user-uploaded assets (images, PDFs, videos)

  • useful .gitignore templates: github.com/github/gitignore.

8.3 Globally ignore files

  • .gitignore is local. What if we want to ignore files in all repositories?

  • user-specific instead of repository-specific

  • git config --global core.excludefile ~/.gitignore_global

    • a good place: in your user directory ~ as it is a user configuration.

  • if you want to ignore files, that you don’t want others to ignore, this setting can be useful.

8.4 Ignore tracked files

  • .gitignore only applied to untracked files. It doesn’t apply it to already tracked files. We tried an example to show this.

  • to stop tracking an already tracked file, it needs to be removed from git but not from the directory.

  • do not use git rm. This removes it from the directory also.

  • Instead use git rm --cached file.txt and git status shows file is deleted. But the file exists in your directory.

  • Now .gitignore for file.txt will ensure that file is not tracked.

  • The file is still in the repository. If someone new checks out this file, it will be available. But future changes will not be tracked. (didn’t fully understand this bit)

8.5 Track empty directories

  • git is designed to be a file tracking system, but it ignores empty directories.

  • for example, explorers directory is empty.

    • git ls-tree HEAD does not list explorers.

  • mkdir temp

    • git status.

    • no changes

  • but sometimes you want empty directories on your repository (for example, if you want users to add photos)

  • if you want to track an empty directory, add a file .gitkeep.

    • now you can add and commit the directory.

  • on a unix machine, touch temp/.gitkeep. Creates the file even if it doesn’t exist.