.gitignore: Ignore a Directory's Contents Except One File

Git does not descend into an ignored directory to find exceptions. To keep build/README.md while ignoring generated files in build/, ignore the contents of the directory and then add an exception for the README.

Worked example

Root .gitignore rules for the build folder

/build/*
!/build/README.md

Steps

  1. In the root .gitignore, replace a rule like /build/ with /build/*, then add the README exception below it. The leading slash limits the patterns to build at the repository root.
  2. Check git status --short --untracked-files=all with a new README and a generated report in build. The README should be visible and the report should be ignored.
  3. If the file to keep is in a deeper subdirectory, make sure every parent directory along its path remains visible. Use git check-ignore -v --no-index on a path to see which rule takes effect.

What to check

  • Within one .gitignore file, the last matching pattern wins. An older /build/ rule that still excludes the whole directory may prevent Git from seeing the README.
  • An already tracked report remains tracked after you add these rules. Use git ls-files on the path if the report still appears as modified.

Generate a baseline .gitignore before adding the exception

References