Depth Control
While -prune is used to exclude specific named paths, depth options are used to categorically limit how far down the directory tree find is allowed to crawl.
Depth options are global options in GNU find. This means they should be placed immediately after the starting path, before any tests or actions.
1. Limiting Descent (-maxdepth)
-maxdepth N tells find to descend at most N levels of directories below the starting point.
-maxdepth 0: Apply tests and actions ONLY to the starting point itself.-maxdepth 1: Process the starting point and files/directories immediately inside it (no subdirectories).-maxdepth 2: Process down to one level of subdirectories.
Example: "ls-like" behavior
If you want to search for a file only in the current directory, without crawling into any folders:
# Fast: Searches only /etc, skips /etc/apache2/, /etc/nginx/, etc.
find /etc -maxdepth 1 -name "*.conf"
2. Delaying Action (-mindepth)
-mindepth N tells find to ignore everything until it has descended N levels.
-mindepth 1: Process everything EXCEPT the starting point itself.
Example: Delete contents, keep the folder
A common administrative task is emptying a directory without deleting the directory itself.
# Fails: This deletes /tmp/cache entirely
find /tmp/cache -delete
# Succeeds: Leaves /tmp/cache intact, deletes everything inside it
find /tmp/cache -mindepth 1 -delete
3. Depth-First Traversal (-depth / -d)
By default, find uses a pre-order traversal (it processes a directory before it processes the contents of that directory).
The -depth flag forces a post-order traversal (it processes the contents of a directory before it processes the directory itself).
Why is -depth necessary?
If you are writing a script to rename directories, or delete trees, you must process the children before the parent. If you rename /foo to /bar, any subsequent attempt by find to read /foo/child.txt will fail because the parent path has changed.
-depth ensures the children are processed and acted upon before the parent is touched.
(Note: The built-in -delete action automatically implies -depth, which is why it is so safe to use).
# Safe renaming script using -depth
find /data -depth -name "*_old" -exec rename '_old' '_new' {} +