Commands.page Logo

How to Limit Depth of Recursive Directory Search Ubuntu

When working with large file systems in Ubuntu, searching every subdirectory can be slow or return too many results. This guide explains how to restrict the recursion level of your search using standard command-line tools. You will learn how to use the -maxdepth flag with the find command to control how many directory levels deep the system looks for files or folders.

Using the Find Command

The primary tool for managing search depth in Ubuntu is the find command. It includes a specific option called -maxdepth that dictates how many levels of subdirectories the command will descend into.

The basic syntax is:

find [path] -maxdepth [level] [expression]

Understanding Depth Levels

It is crucial to understand how Linux counts directory levels:

Practical Examples

To search for files named config.txt only in the current directory without entering any subfolders, use level 0:

find . -maxdepth 0 -name "config.txt"

To search the current directory and one level of subdirectories, use level 1:

find . -maxdepth 1 -name "config.txt"

To search recursively without any limit, you simply omit the -maxdepth flag:

find . -name "config.txt"

Combining with Other Options

You can combine depth limiting with other actions such as deleting files or listing details. For example, to list all .log files within two directory levels of /var/www:

find /var/www -maxdepth 2 -name "*.log" -ls

Using -maxdepth improves performance on large drives by preventing the command from traversing unnecessary deep directory structures. Always place -maxdepth before the expression arguments to ensure correct execution in Ubuntu terminals.