[grep] Exclude directories when searching recursively

Created on November 30, 2026

Use grep -r with --exclude-dir to search subdirectories while skipping ones that match a name pattern.

mkdir -p logs/archive
printf 'ERROR current\n' > logs/app.log
printf 'ERROR old\n' > logs/archive/old.log
grep -r --exclude-dir=archive 'ERROR' logs/
logs/app.log:ERROR current

With --exclude-dir=archive, grep skips directories named archive at any depth and all their contents. Use an option such as --exclude='*.log' to exclude files by name.

Reference

Shell command grep