How to Use a .gitignore file

Introduction

When you make commits in a git repository,
you choose which files to stage to commit.
But what if there are some files that you never want to commit?

How .gitignore Works

A .gitignore file is a plain text file
where each line contains a pattern/directories to ignore.
You can have mutiple .gitignore files.
The patterns in the files are relative to the location of that .gitignore file.

Patterns

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Literal file names
test.py

# Directories
## You can ignore entire directories,
## just by including their paths and putting a slash(/) on the end.
logs/
# If you leave the slash off the end,
# it will match both files and directories.

# Wildcard
## The * matches zero or more characters(except the slash /).
*.log
## You can also use the ?,which matches any one character except for the slash.

# Negation
## You can use a prefix of `!` to negate a file that would be ignored.
!example.log

# Double Asterisk
## ** can be used to match any number of directories.
**/.idea/

Local Repository .gitignore Rules

If there are some files you want to ignore for just this repository,
you can put them in .git/info/exclude

Global .gitignore Rules

If there are some files you want to ignore in all repositories on your computer,
you can put them in a global .gitignore file ~/.gitignore.

1
git config --global core.excludesFile ~/.gitignore

Notes

Git will not ignore the file if you have already committed if.
You have to untrack the file first.

1
2
git rm --cached FILENAME 
git rm -r --cached DIRECTORIES

Debugging

If you’re having trouble,
you can use git check-ignore -v filename/directories

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022-2023 Ataraxia

请我喝杯咖啡吧~