Git Basics: Ignoring Generated Files
A build directory or local log usually does not belong in a commit. A project’s .gitignore records patterns for files Git should leave untracked.
Run these commands in Bash with Git 2.28 or newer installed. Start a fresh temporary repository for this article:
git_practice=$(mktemp -d) || exit
cd "$git_practice" || exit
git init -q -b main
git config user.name 'Practice User'
git config user.email 'practice@example.invalid'
git config commit.gpgsign falseThe identity and signing settings apply only to this repository. Use your own identity in real projects. The temporary files remain afterward. Examples assume default Git settings; if a pager opens, press q to leave it.
Add two rules
printf '/build/\n*.log\n' > .gitignore
mkdir build
printf 'generated output\n' > build/result.txt
printf 'started\n' > app.log
printf 'Practice project\n' > README.md
git status --short?? .gitignore
?? README.md/build/ matches the directory at this repository’s root. *.log matches names ending in .log at any level below this .gitignore. Neither rule deletes a file.
Check what was ignored
git status --short --ignored?? .gitignore
?? README.md
!! app.log
!! build/!! marks ignored paths. To find the exact rule responsible for one file:
git check-ignore -v app.log.gitignore:2:*.log app.logThe fields identify the ignore file, line number, pattern, and path. Git separates the pattern from the path with a tab. This is useful when a file seems to be missing from status output.
Save the shared rules
git add .gitignore README.md
git commit -q -m 'Ignore generated files'
git ls-files.gitignore
README.mdThe committed rules will travel with the project. For a rule that should stay local to this repository, use .git/info/exclude instead.
Ignore rules do not stop tracking a file that is already committed. They also do not erase old commits or protect secrets. If a credential was committed, revoke or rotate it rather than relying on a new ignore rule.
References
Git ignore manual and Git check-ignore manual
Acknowledgements
This post was created with assistance from AI.