How to Ignore Files in Git: Simple Guide
To ignore files in Git, create a
.gitignore file in your repository root and list the file names or patterns you want Git to ignore. Git will then skip tracking those files during commits.Syntax
The .gitignore file contains patterns that tell Git which files or folders to ignore. Each line is a pattern matching file names or directories.
filename: ignores a specific file.foldername/: ignores a folder and its contents.*.ext: ignores all files with the extension.ext.!pattern: negates a pattern, so matching files are not ignored.
gitignore
.gitignore file example: # Ignore all .log files *.log # Ignore the build folder build/ # Ignore a specific file secret.txt # Do not ignore important.log even if *.log is ignored !important.log
Example
This example shows how to ignore log files and a secret file so they are not tracked by Git.
bash
# Create .gitignore file cat > .gitignore <<EOF *.log secret.txt EOF # Check git status before adding files mkdir test_repo && cd test_repo echo "log data" > app.log echo "important data" > important.log echo "secret info" > secret.txt git init git status # Add all files git add . git status
Output
Initialized empty Git repository in /test_repo/.git/
On branch master
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
app.log
important.log
secret.txt
nothing added to commit but untracked files present (use "git add" to track)
# After git add .
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: .gitignore
new file: important.log
# Notice app.log and secret.txt are not added because they are ignored
Common Pitfalls
Common mistakes when ignoring files in Git include:
- Adding files to Git before adding them to
.gitignore. Git will keep tracking them unless you remove them from the index. - Incorrect patterns in
.gitignorethat do not match the intended files. - Forgetting that
.gitignoreonly affects untracked files, not files already tracked.
bash
# Wrong: Adding file before ignoring
git add secret.txt
# Then adding secret.txt to .gitignore does NOT stop tracking
# Correct: Remove from index first
git rm --cached secret.txt
# Now Git will ignore secret.txt as per .gitignoreQuick Reference
| Pattern | Meaning |
|---|---|
| *.log | Ignore all files ending with .log |
| build/ | Ignore the build directory and its contents |
| secret.txt | Ignore the file named secret.txt |
| !important.log | Do not ignore important.log even if *.log is ignored |
Key Takeaways
Use a .gitignore file to list files or patterns Git should ignore.
Patterns in .gitignore can match files, folders, or extensions.
Git only ignores untracked files; remove tracked files from index to ignore them.
Check your .gitignore syntax carefully to avoid mistakes.
Use git rm --cached to stop tracking files already added to Git.