How to Ignore a Folder in Git: Simple .gitignore Guide
To ignore a folder in Git, add its path followed by a slash to a
.gitignore file, for example foldername/. This tells Git to skip tracking all files inside that folder.Syntax
The basic syntax to ignore a folder in Git is to add the folder name followed by a slash / in the .gitignore file.
foldername/: Ignores the entire folder and its contents.subfolder/foldername/: Ignores a folder inside a subfolder./*.log: Ignores all files with .log extension in the root folder (not a folder example but useful).
plaintext
# .gitignore # Ignore the folder named 'logs' logs/ # Ignore a folder inside 'src' src/temp/
Example
This example shows how to ignore a folder named cache in your Git project. After adding cache/ to .gitignore, Git will not track any files inside the cache folder.
bash
# Create .gitignore file echo "cache/" > .gitignore # Check git status before adding files mkdir cache echo "temp data" > cache/data.txt git init git status # Add .gitignore and commit git add .gitignore git commit -m "Add .gitignore to ignore cache folder" # Check git status again git status
Output
On branch master
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
cache/
nothing added to commit but untracked files present (use "git add" to track)
[master (root-commit) 1a2b3c4] Add .gitignore to ignore cache folder
1 file changed, 1 insertion(+)
create mode 100644 .gitignore
On branch master
nothing to commit, working tree clean
Common Pitfalls
Common mistakes when ignoring folders in Git include:
- Not adding the trailing slash
/after the folder name, which can cause Git to ignore files with the folder name but not the folder itself. - Trying to ignore a folder that is already tracked by Git;
.gitignoreonly affects untracked files. - Incorrect folder path in
.gitignoreif the folder is nested.
plaintext
# Wrong: missing trailing slash, ignores files named 'cache' but not the folder
cache
# Right: with trailing slash, ignores the folder and contents
cache/
# If folder is already tracked, remove it first
git rm -r --cached cache/
# Then commit and .gitignore will work
Quick Reference
| Pattern | Effect |
|---|---|
| foldername/ | Ignore entire folder and contents |
| foldername/*.log | Ignore all .log files inside foldername |
| /foldername/ | Ignore foldername only in root directory |
| **/foldername/ | Ignore foldername anywhere in the project |
| !foldername/ | Do not ignore foldername if previously ignored |
Key Takeaways
Add the folder name with a trailing slash in .gitignore to ignore it.
.gitignore only affects untracked files; remove tracked folders first to ignore them.
Use correct folder paths for nested folders in .gitignore.
A missing trailing slash means Git ignores files named like the folder, not the folder itself.
Use ! prefix to unignore folders if needed.