The Infinite Loop
By default, the Linux find command is entirely recursive. If you tell it to search the root directory (/), it will aggressively scan every single folder, sub-folder, and file on your entire hard drive until it reaches the absolute bottom of the file system tree. If you are auditing a massive server with millions of files, this can take hours and consume a massive amount of CPU power. If you only want to search the immediate files inside a specific directory without diving into its sub-folders, you must artificially restrict the search algorithm’s penetration depth.
Using the find Command with -maxdepth
The Linux find command utilizes the -maxdepth flag to explicitly define exactly how many folder levels the engine is allowed to traverse.
- Open your Terminal application (Ctrl + Alt + T) or log into your server via SSH.
- To scan the
/var/log/directory, but only look at the files sitting directly inside it (ignoring all sub-folders like/var/log/nginx/), type the following command exactly: find /var/log/ -maxdepth 1 -type f -name "*.log"- Press Enter.
Targeted Searching
The -maxdepth 1 argument restricts the search strictly to the current directory. If you change it to -maxdepth 2, the search engine will scan the current directory and immediately stop after scanning one folder deeper. Crucially: The -maxdepth flag must be placed immediately after the starting directory path, before any other arguments like -name or -type, otherwise the search engine will generate a warning error.