Searching directory trees with find
- Version
- unversioned
- Review
- Draft
Summary#
find walks a directory tree and applies tests and actions to each entry, from left to right. It prints matching paths when the expression has no action of its own.
Syntax#
find start_path -type f -name '*.log'
find start_path -name node_modules -prune -o -type f -print
find start_path -type f -name '*.log' -exec command {} +
find start_path -type f -name '*.tmp' -delete
-exec command {} + passes paths in batches. End the command with \; to run it once per path.
Example#
(
set -eu
export LC_ALL=C
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
mkdir -p app/logs app/node_modules/pkg
: > app/main.js
: > app/logs/error.log
: > 'app/logs/debug run.log'
: > app/logs/cache.tmp
: > app/node_modules/pkg/index.js
find app -type f -name '*.log' | sort
echo '-- JavaScript outside node_modules'
find app -name node_modules -prune -o -type f -name '*.js' -print
echo '-- delete temporary files, then count what is left'
find app -type f -name '*.tmp' -delete
find app -type f -name '*.tmp' -exec echo {} \; | wc -l
)
Expected output#
app/logs/debug run.log
app/logs/error.log
-- JavaScript outside node_modules
app/main.js
-- delete temporary files, then count what is left
0
Common mistakes#
Put -delete after the tests or it can remove the whole tree. Preview with -depth and the same tests followed by -print. -delete implies -depth, which visits children before their parent and makes -prune ineffective. Quote patterns such as '*.log' so the shell does not expand them before find sees them.
Version applicability#
This entry describes GNU findutils find. BSD and macOS find require a starting path and have a different set of extensions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0