.gitignore and git check-ignore
- Version
- 2.51
- Review
- Draft
Summary#
Share ignore rules for generated or local files in .gitignore. For patterns in one file, the last match wins. Prefix an exception with !. git check-ignore -v shows the matching rule and where it came from.
Syntax#
*.cache
!baseline.cache
git check-ignore -v -- scratch.cache
git check-ignore -v --no-index -- old.cache
git rm --cached -- old.cache
Example#
(
set -eu
scratch=$(mktemp -d "${TMPDIR:-/tmp}/devlookup-git.XXXXXX")
trap 'rm -rf -- "$scratch"' EXIT
unset GIT_CONFIG_GLOBAL $(git rev-parse --local-env-vars)
export GIT_CONFIG_NOSYSTEM=1 GIT_TEMPLATE_DIR= LC_ALL=C
export HOME="$scratch" XDG_CONFIG_HOME="$scratch" GIT_ATTR_NOSYSTEM=1
mkdir "$scratch/work"
cd "$scratch/work"
git init -q -b trunk
git config core.excludesFile /dev/null
printf 'local contents\n' > old.cache
git add -- old.cache
git -c user.name="Reference Example" -c user.email=example@example.invalid commit -qm "Track cache"
printf '*.cache\n!baseline.cache\n' > .gitignore
touch scratch.cache baseline.cache
git check-ignore -v -- scratch.cache
git status --short -- baseline.cache
printf 'tracked: %s\n' "$(git ls-files -- old.cache)"
git rm --cached -- old.cache > /dev/null
printf 'kept on disk: %s\n' "$(cat old.cache)"
git check-ignore -v -- old.cache
)
Expected output#
.gitignore:1:*.cache scratch.cache
?? baseline.cache
tracked: old.cache
kept on disk: local contents
.gitignore:1:*.cache old.cache
Common mistakes#
An exception cannot restore a file inside a directory Git skips entirely. Ignore the directory's contents if you need exceptions inside it. Already-tracked files stay tracked. Use --no-index to debug their rules and git rm --cached to keep a working copy while staging removal from the repository. Committing that removal affects everyone who pulls it.
Version applicability#
Git 1.8.2 added git check-ignore, and Git 1.8.5 added its --no-index flag. The complete example requires Git 2.28 or later for git init -b.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0