- Linux Shell Scripting Cookbook(Third Edition)
- Clif Flynt Sarath Lakshman Shantanu Tushar
- 434字
- 2021-07-09 19:46:14
Searching based on the directory depth
The find command walks through all the subdirectories until it reaches the bottom of each subdirectory tree. By default, the find command will not follow symbolic links. The -L option will force it to follow symbolic links. If a link references a link that points to the original, find will be stuck in a loop.
The -maxdepth and -mindepth parameters restrict how far the find command will traverse. This will break the find command from an otherwise infinite search.
The /proc filesystem contains information about your system and running tasks. The folder hierarchy for a task is quite deep and includes symbolic links that loop back on themselves. Each process running your system has an entry in proc, named for the process ID. Under each process ID is a folder called cwd, which is a link to that task's current working directory.
The following example shows how to list all the tasks that are running in a folder with a file named bundlemaker.def:
$ find -L /proc -maxdepth 3 -name 'bundlemaker.def' 2>/dev/null
- The -L option tells the find command to follow symbolic links
- The /proc is a folder to start searching
- The -maxdepth 3 option limits the search to only the current folder, not subfolders
- The -name 'bundlemaker.def' option is the file to search for
- The 2>/dev/null redirects error messages about recursive loops to the null device
The -mindepth option is similar to -maxdepth, but it sets the minimum depth for which find will report matches. It can be used to find and print files that are located with a minimum level of depth from the base path. For example, to print all files whose names begin with f and that are at least two subdirectories distant from the current directory, use the following command:
$ find . -mindepth 2 -name "f*" -print ./dir1/dir2/file1 ./dir3/dir4/f2
Files with names starting with f in the current directory or in dir1 and dir3 will not be printed.