The Wayback Machine - https://web.archive.org/web/20240927004704/https://www.geeksforgeeks.org/mindepth-maxdepth-linux-find-command-limiting-search-specific-directory/
Open In App

mindepth and maxdepth in Linux find() command for limiting search to a specific directory.

Last Updated : 19 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

How to limit search a specified directory in Linux?

There is a command in Linux to search for files in a directory hierarchy known as

‘find’

. It searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence, until the outcome is known (the left-hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.’ is assumed. The find command by default travels down the entire directory tree recursively, which is time and resource consuming. However the depth of directory traversal can be specified(which are

mindepth

and

maxdepth

).

What are mindepth and maxdepth levels?

  • maxdepth levels : Descend at most levels (a non-negative integer) levels of directories below the starting-points. -maxdepth 0 means only apply the tests and actions to the starting-points themselves.
  • mindepth levels : Do not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files except the starting-points.

Given below some examples to illustrate how depth of the directory traversal can be specified using

mindepth

and

maxdepth

  • Find the passwd file under all sub-directories starting from the root directory.
    find / -name passwd
    step1-1
  • Find the passwd file under root and one level down. (i.e root — level 1, and one sub-directory — level 2)
    find / -maxdepth 2 -name passwd
  • Find the passwd file under root and two levels down. (i.e root — level 1, and two sub-directories — level 2 and 3 )
    find / -maxdepth 3 -name passwd
  • Find the password file between sub-directory level 2 and 4.
    find / -mindepth 3 -maxdepth 5 -name passwd

There are two other ways to limit search a directory in linux :

grep Grep searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN.By default, grep prints the matching lines.

Examples of grep :

You can search the current directory with grep as follows:



To check whether a directory exists or not


Find the directory under root directory.


Find the directory under root and one levels down.





ack Ack is designed as a replacement for 99% of the uses of grep. Ack searches the named input FILEs (or standard input if no files are named, or the file name – is given) for lines containing a match to the given PATTERN. By default, ack prints the matching lines. Ack can also list files that would be searched, without actually searching them, to let you take advantage of ack’s file-type filtering capabilities. Ack does not have a max-depth option

Examples of ack :

To check a particular directory under the root






mindepth and maxdepth in Linux find() command for limiting search to a specific directory. – FAQs

What do mindepth and maxdepth do in the find command?

In the find command in Linux, mindepth and maxdepth are options used to limit the depth of directory traversal:

  • mindepth: Controls how deep find starts to report results. If you specify mindepth as 2, find will ignore everything at depth 1 (the top-level directory) and start reporting from depth 2.
  • maxdepth: Limits how far down in the directory structure find will go to look for matches. If you specify maxdepth as 1, find will only look at the direct children of the directories specified and no further.

How to use mindepth to limit search results in Linux?

To use mindepth in the find command, specify it followed by the minimum depth you want find to start reporting results. For example, to find all .txt files starting from subdirectories two levels down from the current directory:

find . -mindepth 2 -name "*.txt"

This command will not report .txt files in the current directory or its immediate subdirectories but will start from subdirectories two levels deep.

How to use maxdepth to limit search results in Linux?

To use maxdepth in the find command, specify it followed by the maximum depth you want find to search. For example, to find all .txt files in the current directory and its immediate subdirectories:

find . -mindepth 2 -name "*.txt"

This command will look for .txt files in the current directory (depth 1) and its immediate subdirectories (depth 2).

Can mindepth and maxdepth be used together in find?

Yes, mindepth and maxdepth can be used together in a single find command to finely control the search depth. For example, to find files only in subdirectories exactly two levels deep, you can set both mindepth and maxdepth to 2:

find . -mindepth 2 -maxdepth 2 -name "*.txt"

This command will only find .txt files that are located exactly two directories beneath the current directory.

What are some examples of using mindepth and maxdepth in real scenarios?

Here are a couple of practical examples where mindepth and maxdepth can be particularly useful:

1. Backup Scripts: When creating backups, you might want to exclude the top directory or include only specific subdirectory levels. For instance, backing up only the second-level directories of a project:

find /project -mindepth 2 -maxdepth 2 -type d -exec tar -cvzf {}.tar.gz {} \;

2. System Administration: Searching for specific types of files within a controlled depth range for performance reasons, like finding all log files within the first three levels of /var/log:

find /var/log -maxdepth 3 -name "*.log"

3. Cleaning Up Temporary Files: Removing temporary files that are not within the top-level temporary directories, ensuring that directory structure is preserved:

find /tmp -mindepth 2 -name "*.tmp" -delete


Similar Reads

How to use 'cp' command to exclude a specific directory
cp command is used to create an exact copy of the contents of the files and directories but with a different name and location. It works using the terminal. The exact syntax goes like this: Syntax:cp [source_file/directory] [destination]Where cp is used for the copy, source_file provides the exact file or directory or folder from where you want to
3 min read
How to Create Directory in Linux | mkdir Command
In Linux, the 'mkdir' command is like a magic wand for creating folders super easily. 'mkdir' stands for "make directory," and it helps you organize your computer stuff by creating folders with just one command. Whether you're making one folder or a bunch of them in a row, 'mkdir' is there to help you keep things neat and tidy on your computer. In
7 min read
How to Display Current Working Directory in Linux | pwd Command
The 'pwd,' which stands for "print working directory." In this article, we will delve into the 'pwd' command, exploring its functionality, usage, and various examples. It prints the path of the working directory, starting from the root. pwd is shell built-in command(pwd) or an actual binary(/bin/pwd). $PWD is an environment variable that stores the
4 min read
How to Change the Directory in Linux | cd Command
Mastering the cd command in Linux is a fundamental skill for anyone working in the Linux environment. The cd command allows you to change directories in Linux, making it easier to navigate through the file system and manage your files efficiently. Whether you're a beginner or an experienced user, understanding how to use the cd command in Linux is
6 min read
Shell Script to Delete a File from Every Directory Above the Present Working Directory
In this article, we will discuss how to delete a file from every directory above the parent working directory using shell script in Linux. To delete a file from a directory we use the rm command in Linux/UNIX. Syntax: rm [OPTION]... [FILE]... Using shell script, we have to delete the input file from every directory above the present working directo
2 min read
Ccat – Colorize Cat Command Output command in Linux with Examples
ccat is a command-line tool for Linux and OSX, which is similar to the cat command in Linux. But the difference between cat and ccat is that the ccat shows the content of the file with the syntax highlighted. Currently, ccat supports the following programming languages. JavaScriptJavaRubyPythonGoCJSONInstallation of Ccat First, we are going to see
2 min read
How to Display Command History in Linux | history Command
The command-line interface in Linux provides powerful tools for users, and mastering command history is essential for efficient navigation and retrieval of previously executed commands. The history command is a valuable utility that allows users to view and search through their command history. In this comprehensive guide, we will explore the vario
4 min read
Find and Replace with sed in Directory and Sub Directories in Linux
sed stands for stream editor. It is a basic utility command in Linux that has basic functionality like inserting, deleting, finding, replacing, and searching text strings in a file. But sed is most commonly used for its substitution function i.e find and replace. Syntaxsed OPTIONS... [script] [input_file] e.g. sed "s/abc/ABC/g" abc.txt Consider the
4 min read
bd – Quickly Go Back to a Parent Directory Instead of Typing ‘cd’ Command
IntroductionEvery Linux user most probably suffers in a situation where we need to jump from one directory to another in a backward direction, multiple times. Conventionally most of us choose to use the '..' parameter with the 'cd' command to denote the previous directory, multiple times. This command might look like this, 'cd ../../../..'. This co
6 min read
How to Make File and Directory Undeletable Even By Root in Linux?
In this article, we are going to see How to Make File and Directory Undeletable, Even By Root in Linux. So in order to make a file or directory undeletable by any user, we need to make the file or directory unmodifiable using the chattr command. This command changes the file attributes in our system. So in order to make it Undeletable Syntax is: No
2 min read
Renaming All Files and Directory Names to Lowercase in Linux
Here we will see how to rename all files and directory names to lowercase in Linux. We can easily do it with some basic commands in Linux. The below command can be used to view the contents of your directory. $ find [directory_name] -depth Here 'priyanshu' directory which has some sub-files/folders, has all files starting from uppercase letters: $
1 min read
Copy and Create Destination Directory if it Does Not Exist in Linux
A directory is a file system location for storing and organizing files. A Linux system has many directories, and users can create their own directories. Copying and creating a directory are useful operations for Linux users. To create a new directory, use the command: mkdir new_directory. The 'm' stands for 'modify.' The name of the new directory m
6 min read
Linux Shell Script to Backup Files and Directory
Backing up our important files and directories is crucial to safeguarding our data. In this article, we’ll create a simple shell script that uses the tar utility to create an archive file for backup purposes that we can use whenever we require. The shell script we’ll build allows us to specify which directories to back up and where to store the bac
5 min read
How to Find a File in Linux | Find Command
Linux, renowned for its robust command-line interface, provides a suite of powerful tools for efficient file and directory management. Among these, the "find" command stands out as an indispensable asset, offering unparalleled versatility in searching for files based on diverse criteria. This article explores the prowess of the find command, sheddi
9 min read
Watcherd Shell Listener for Directory Changes in Linux
Watcherd is a tool for Linux that helps to monitor directory changes and print whatever changes are done like adding and deleting for a particular directory and execute commands and shell scripts according to a particular event. Installing Watcherd on Linux Step 1: Downloading watcherd. Since watcherd is a Github repository you can use wget command
2 min read
Linux Directory Structure
Prerequisite: Linux File Hierarchy Structure In Linux/Unix operating system everything is a file even directories are files, files are files, and devices like mouse, keyboard, printer, etc are also files. Here we are going to see the Directory Structure in Linux. Types of files in the Linux system. General Files - It is also called ordinary files.
5 min read
OpenDoor - OWASP Directory Access Scanner in Kali Linux
Brute-Forcing is an automated process through which Usernames, Passwords can be detected by querying the possible credentials on the target domain login pages. We can also brute-force hidden files and directories on the target server by specifying the possible word-list which contains the phrases that will be tested on the domain. This process save
3 min read
How to Get Total Size of a Directory in Linux
Many times during working on Linux we may encounter situations, where we want to look at the total size occupied by a directory. Knowing the file or directory size can help a user perform tasks like storage allocation, size comparison, etc. At that time knowledge of some commands might be helpful to get the size of a directory in Linux. Usually, wh
5 min read
How to Copy a Directory in Linux
There is this famous quote for Linux by Jamie Zawinski that goes like this "Linux is only free if your time has no value." Certainly, that's true as people start using Linux they have to learn more about it, and when encountering it we have to solve it by ourselves, and that way we learn more about Linux. In this article, we are going to learn how
5 min read
How to Fix - Unable to Lock the Administration Directory – Kali Linux
Kali Linux is among the most famous OS for ethical hacking and pentesting. It contains all the necessary tools for pentesting and ethical hacking. Using Kali is not easy and every user has once encountered errors. In this article, we will see how to solve this particular problem using Kali Linux. What is Unable to lock the administration directory
5 min read
bash: cd: Downloads: No such file or directory in Linux
Encountering errors while navigating through the command line interface can be frustrating, especially for beginners. One common error, "Bash: Cd: Downloads: No Such File Or Directory," often occurs when users attempt to change directories to a location that doesn't exist or isn't accessible. However, fear not! This article serves as a comprehensiv
4 min read
How to Count Files in Directory Recursively in Linux
When exploring directories on your server, you may have come across folders with a large number of files in them. You might wish to know how many files exist in a certain directory or across many directories at times. To put it another way, you wish to count the number of files saved in a directory on your system. In this article, we are going to s
5 min read
DotDotPwn - Directory Traversal Fuzzer Tool in Linux
Directories in the Web-based application hold various information about the functionalities of the website. Some directories can be common or usual, but some of the directories are attractive or important directories that can contain some important information. Like /etc/passwd can contain the information about the Linux server. Traversing this dir
4 min read
How to Remove Directory in Linux
In Linux, a Directory is a container for files and other directories, forming a hierarchical structure. So, before diving deep into the directory, let's learn about the Linux Directory. A directory is a structure that plays an important role in the file system, offering users a systematic way to navigate and structure their data. The Linux System D
5 min read
How to Find all Files Containing Specific Text (string) on Linux
Suppose you are looking for a file in Linux, but you have forgotten its name. You only remember the contents of the file. How will you find the file in this case? Well, there are some useful methods that will help you find a file containing a specific text (or string) in Linux. The string needs to be specified by the user. So, let's take a look at
4 min read
Difference between locate, which and find Command in Linux
There are a number of Linux utilities that can be used to locate files in a Linux installation with three of the most common being find, locate, and which. All three of these utilities have similar functions, but work and return data in different ways. In this article, we are going to discuss these three useful and powerful command-line utilities t
5 min read
Linux - Installing locate Command to Find Files
In this article, we will see how to install locate command to find files in Linux. locate is a command-line interface tool used for finding files by name in Linux systems. This works more efficiently than other commands. It uses one or more databases by updatedb. To check whether locate utility is already installed in your system. Open up your term
2 min read
How to Exclude Certain Paths With the find Command in Linux
The find command in Linux is a very useful command line utility that helps us in finding files and directories. In our daily life, there are many tasks in which we require files that may be located deep inside the system, finding them manually would be a tedious task. Thus, the find command comes in handy. We can improve the performance of this com
3 min read
How to find time taken by a command/program on Linux Shell?
We have already discussed a way to find time taken by a function through C libraries. If we are on Linux, then it becomes very easy to find time taken by a program/command. We can use time command for this purpose. The time taken is shown in three forms. real: Total end to end time taken by program/command user: Time taken in user mode. sys: Time t
1 min read
How to Find Your IP Address in Linux | ifconfig Command
Knowing your IP address is fundamental for network administration, troubleshooting, and various Linux system tasks. In this article, we will explore several methods to find your IP address in a Linux environment. Whether you are a seasoned Linux user or just getting started, understanding these methods will empower you to navigate and manage your n
9 min read