Git .gitignore
A shop's display window shows the things customers came for. The empty boxes, the cleaning cloths and the staff lunch stay in the back room. Nobody throws them away, but nobody puts them in the window either.
Your project folder has a back room too. Compiled .class files, log files, editor settings and files with passwords all live next to your code, but they don't belong in the repository. A file called .gitignore tells Git which files to leave out, so they stop appearing in git status and can't be committed by accident.
In this lesson, you will write a .gitignore file, learn its patterns, see what to do about files that were committed before you ignored them, and find out why Git ignores a particular file.
The Problem
Navika's Java project has a committed README and a guide in docs/. Running the app and the build has left other files behind:
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo "Fee Tracker" > README.md
mkdir docs
echo "How to add a fee" > docs/guide.md
git add .
git commit --quiet -m "Add README and guide"
mkdir target
echo "compiled" > target/App.class
echo "started" > app.log
echo "failed" > error.log
echo "DB_PASSWORD=chalk42" > .env
git status -s?? .env
?? app.log
?? error.log
?? target/Every one of these is noise. target/ holds build output that the build can make again. The logs change every time the app runs. .env holds a password. If Navika ran git add . now, all of them would be committed.
Create a .gitignore File
A .gitignore file is a plain text file in the top folder of the repository, with one pattern per line. Navika writes one with three patterns and a comment above each:
cat > .gitignore <<'EOF'
# Build output
target/
# Log files
*.log
# Local settings with passwords
.env
EOF
git status -s?? .gitignorecat > .gitignore <<'EOF' writes the lines up to EOF into the file. In daily work, you would create .gitignore in your editor.
The noise is gone. The only new file left is .gitignore itself, and it should be committed, so that everyone who clones the repository ignores the same files:
git add .gitignore
git commit --quiet -m "Ignore build output, logs and local settings"
git status -s
git status -s --ignored!! .env
!! app.log
!! error.log
!! target/The first git status -s prints nothing: the working tree is clean. --ignored shows what Git is quietly leaving out, each marked with !!.
Pattern Rules
| Pattern | Matches | Example matches |
|---|---|---|
app.log | A file or folder with this name, in any folder | app.log, logs/app.log |
*.log | Any name ending in .log, in any folder. * matches any characters except /. | error.log, logs/debug.log |
target/ | A folder named target, anywhere, with everything in it. The ending / means "folders only". | target/, api/target/ |
/TODO.txt | TODO.txt in the same folder as the .gitignore only. A starting / anchors the pattern. | TODO.txt, but not docs/TODO.txt |
docs/*.pdf | A pattern with a / in the middle is relative to the .gitignore folder | docs/fees.pdf, but not docs/old/fees.pdf |
**/temp | temp in any folder at any depth | temp, a/b/temp |
docs/**/*.pdf | .pdf files anywhere under docs | docs/fees.pdf, docs/old/fees.pdf |
report-?.txt | ? matches exactly one character | report-1.txt, report-A.txt |
!keep.log | Negation: do not ignore this, even if an earlier pattern did | keep.log |
# text | A comment. Empty lines are ignored too. | nothing |
Anchor a Pattern to One Folder
Without a /, a name matches in every folder. Navika wants to ignore her own TODO.txt at the top of the project, but the team's docs/TODO.txt must be committed:
echo "my list" > TODO.txt
echo "team list" > docs/TODO.txt
echo "/TODO.txt" >> .gitignore
git status -s M .gitignore
?? docs/TODO.txtThe starting / makes the pattern match only next to the .gitignore file. docs/TODO.txt is still reported, ready to be added. Without the /, both files would be ignored.
Make an Exception with !
A ! at the start of a pattern takes a file back out of the ignored set. The office needs one log file, audit.log, committed:
echo "!audit.log" >> .gitignore
echo "paid" > audit.log
git status -s M .gitignore
?? audit.log
?? docs/TODO.txt*.log still ignores app.log and error.log, but the later !audit.log brings audit.log back. Order matters: inside one file, the last pattern that matches a path wins.
Navika commits the work so far:
git add .
git commit --quiet -m "Add the team TODO and the audit log"
git log --oneline -18b5d481 (HEAD -> main) Add the team TODO and the audit logA .gitignore in a Subfolder
A .gitignore can also live in a subfolder. Its patterns apply only inside that folder, which keeps rules close to the files they are about:
echo "*.draft" > docs/.gitignore
echo "draft" > docs/intro.draft
echo "draft" > intro.draft
git status -s?? docs/.gitignore
?? intro.draftdocs/intro.draft is ignored by docs/.gitignore. intro.draft at the top is not, because that rule doesn't reach outside docs. The new docs/.gitignore is reported, to be committed like any other file:
git add docs/.gitignore
git commit --quiet -m "Ignore drafts in docs"
git status -s?? intro.draftintro.draft stays untracked for now. You will see it in the next few outputs.
Find Out Why a File Is Ignored
When a file doesn't show up and you don't know why, ask Git. git check-ignore -v prints the file, the line number and the pattern responsible:
git check-ignore -v app.log target/App.class TODO.txt docs/intro.draft.gitignore:4:*.log app.log
.gitignore:2:target/ target/App.class
.gitignore:7:/TODO.txt TODO.txt
docs/.gitignore:1:*.draft docs/intro.draftEach line reads <file that has the rule>:<line number>:<pattern>, then a tab and the path you asked about. app.log is ignored by line 4 of .gitignore, the *.log pattern. A path that is not ignored prints nothing.
Syntax
git check-ignore -v <path>...| Command | It is used to |
|---|---|
git check-ignore -v <path> | Show which file, line and pattern ignore a path |
git status --ignored | List ignored files along with the normal status |
git add -f <file> | Add a file even though it is ignored |
Files That Are Already Tracked
.gitignore only affects untracked files. A file that is already committed stays tracked, whatever the patterns say. Suppose settings.properties was committed, and Navika ignores it afterward:
echo "theme=light" > settings.properties
git add settings.properties
git commit --quiet -m "Add settings"
echo "settings.properties" >> .gitignore
echo "theme=dark" > settings.properties
git status -s M .gitignore
M settings.properties
?? intro.draftsettings.properties is reported as modified ( M), even though it is in .gitignore. To make the rule apply, stop tracking the file with git rm --cached, as in the previous lesson. The file stays on disk, and from then on it is ignored:
git rm --cached --quiet settings.properties
git add .gitignore
git commit --quiet -m "Stop tracking local settings"
git status -s?? intro.draftThe only line left is intro.draft, which no pattern covers. settings.properties is now ignored. Teammates who pull this commit lose their tracked copy of the file, so tell them, and give them a sample file such as settings.example.properties to copy.
Adding an Ignored File on Purpose
If you name an ignored file in git add, Git refuses and tells you why:
git add app.logThe following paths are ignored by one of your .gitignore files:
app.log
hint: Use -f if you really want to add them.
hint: Disable this message with "git config set advice.addIgnoredFile false"-f (force) adds it anyway. After that, the file is tracked, and like settings.properties before, the ignore rule no longer applies to it. Use this only when you are sure, and usually, a ! exception in .gitignore is the clearer choice, because it tells the whole team.
Ignore Files Only for Yourself
Some files are about you, not the project: your operating system's .DS_Store, your editor's settings, your private notes. They shouldn't be in the shared .gitignore. Git reads two more places that are never committed.
1. Your global ignore file, for every repository on your computer. Create the file and tell Git where it is:
echo ".DS_Store" > ~/.gitignore_global
git config --global core.excludesFile "~/.gitignore_global"
echo "x" > .DS_Store
git status -s?? intro.draft.DS_Store doesn't appear in any repository on this computer now.
2. .git/info/exclude, for one repository only. It uses the same patterns as .gitignore, but it lives inside .git, so it is never shared:
echo "my-notes.txt" >> .git/info/exclude
echo "remember the hostel fee" > my-notes.txt
git status -s?? intro.draft| Where | Applies to | Shared with the team? | Use it for |
|---|---|---|---|
.gitignore (any folder) | This repository | Yes, it is committed | Build output, logs, secrets: anything every clone should ignore |
.git/info/exclude | This repository | No | Your own files in one project |
The file in core.excludesFile | Every repository on your computer | No | Operating system and editor files |
Empty Folders and .gitkeep
Git tracks files, not folders. A folder with nothing in it is invisible to Git:
mkdir uploads
git status -s?? intro.draftOnly intro.draft from before appears. To keep an empty folder in the repository, the common habit is to put an empty file called .gitkeep in it. The name means nothing to Git. It is only a convention that tells people why the file exists:
touch uploads/.gitkeep
git status -s?? intro.draft
?? uploads/Now uploads/ appears, because it contains a file. Often the folder should exist, but the files that the app later saves in it should not be committed. Two lines in .gitignore handle that: uploads/* ignores everything inside, and !uploads/.gitkeep brings back the one placeholder.
In Practice
Most projects start from a ready-made .gitignore for their language. GitHub publishes a collection of templates, and GitHub, GitLab and Bitbucket all offer one when you create a repository. For a Java project built with Maven or Gradle, a typical file looks like this:
# Compiled code and build output
*.class
target/
build/
.gradle/
# Packaged files
*.jar
*.war
# Logs
*.log
# IDE settings
.idea/
*.iml
.vscode/
# Local settings and secrets
.envStart with a template, then add the lines your project needs. The Java-specific setup is covered in more detail in the lessons on Git for Java projects, later in the course.
Common Mistakes
Adding a file to .gitignore after it was committed, and expecting it to disappear. Ignore rules apply only to untracked files. Run git rm --cached <file> and commit.
Forgetting to commit .gitignore. Your teammates then don't have the rules and commit the same noise.
Committing secrets "just this once". Once a password is in a commit, it is in the history. Ignore .env and similar files from the very first commit, and change any password that was committed.
Putting personal files in the shared .gitignore. .DS_Store or your editor's folder belong in your global ignore file, so the project's file stays about the project.
Trying to re-include a file inside an ignored folder. target/ plus !target/keep.txt doesn't work. Use target/* and then the ! line.
Guessing why a file is ignored. Run git check-ignore -v <file>, and Git tells you the exact file, line and pattern.
Under the Hood
When Git decides whether an untracked path is ignored, it collects patterns from several places, checked in this order of priority, highest first:
- Patterns given on the command line, for commands that accept them.
.gitignorefiles, the one closest to the file first. A rule indocs/.gitignoreoverrides one in the top.gitignorefor files indocs..git/info/exclude.- The file named by
core.excludesFile. If you never set it, Git uses~/.config/git/ignorewhen that file exists.
Inside each file, the last matching pattern wins, which is why !audit.log worked after *.log.
Ignoring also changes how fast Git is. When a whole folder like target/ is ignored, git status doesn't look inside it at all, which matters when a build has left thousands of files there. It is also the reason a ! pattern can't reach into an ignored folder.
Interview Corner
What is .gitignore used for?
It lists patterns for untracked files that Git should ignore, such as build output, logs, dependencies and local secrets. Ignored files don't appear in git status and aren't added by git add .. The file is committed, so the whole team shares the same rules.
You added a file to .gitignore, but Git still shows changes to it. Why?
The file is already tracked, and .gitignore only affects untracked files. Run git rm --cached <file> to stop tracking it while keeping it on disk, and commit that together with the .gitignore change.
How do you find out why a file is ignored?
git check-ignore -v <file>. It prints the source file, the line number and the matching pattern. git status --ignored lists all ignored files.
What is the difference between .gitignore, .git/info/exclude and the global ignore file?
.gitignore is committed and shared with everyone. .git/info/exclude uses the same format but lives inside .git, so it applies to one repository and is never shared. The global ignore file, set with core.excludesFile, applies to every repository for one user and is used for operating system and editor files.
How do you commit an empty folder?
You can't directly, because Git tracks files, not folders. Put a placeholder file in it, usually an empty file named .gitkeep, and commit that. .gitkeep is only a naming convention, not a Git feature.
Practice
Challenge: what is left? Continue in the same repository. Add these three lines to .gitignore: *.tmp, !report.tmp and cache/. Then create a.tmp, report.tmp, cache/data.txt and notes/cache.txt, and print the short status.
What does Git print? Remember that intro.draft and uploads/ are still waiting from earlier. Before you open the solution, decide which of the four new files appear.
Show solution
printf "*.tmp\n!report.tmp\ncache/\n" >> .gitignore
echo "x" > a.tmp
echo "x" > report.tmp
mkdir cache notes
echo "x" > cache/data.txt
echo "x" > notes/cache.txt
git status -s M .gitignore
?? intro.draft
?? notes/
?? report.tmp
?? uploads/a.tmp is ignored by *.tmp. report.tmp comes back because of !report.tmp, the later pattern. cache/data.txt is ignored because its folder matches cache/. notes/cache.txt is not ignored: cache/ matches only a folder named cache, not a file with that name, so notes/ shows up as a new folder. .gitignore itself shows M because you just changed it.
Checkpoint. Open a project of your own, run git status --ignored, and check every !! line with git check-ignore -v. Then list three files that should be ignored and aren't, and add patterns for them.
Key Takeaways
Quick reference
| Command or file | It is used to |
|---|---|
.gitignore | List patterns to ignore, shared with the team |
git status --ignored | Show ignored files as !! |
git check-ignore -v <path> | Show which pattern ignores a path |
git rm --cached <file> | Stop tracking a file so .gitignore applies to it |
git add -f <file> | Add an ignored file anyway |
.git/info/exclude | Ignore files in one repository, only for you |
git config --global core.excludesFile <file> | Set a personal ignore file for every repository |
.gitkeep | Keep an otherwise empty folder in the repository |
Was this tutorial helpful?