How to use `-maxdepth` option?

The -maxdepth option in the find command is used to limit the search to a specified number of directory levels. This can be useful when you want to restrict the search to a certain depth in the directory hierarchy.

Syntax

find [path] -maxdepth [levels] [other options]

Example Usage

  1. Search in the Current Directory Only
    To find all .txt files in the current directory without descending into subdirectories:

    find . -maxdepth 1 -name "*.txt"
  2. Search Up to Two Levels Deep
    To find all .jpg files in the current directory and one level down (subdirectories):

    find . -maxdepth 2 -name "*.jpg"
  3. Search in a Specific Directory
    To find all directories named backup within a specific directory (e.g., /home/user) but not going deeper than one level:

    find /home/user -maxdepth 1 -type d -name "backup"

Explanation

  • . refers to the current directory.
  • -maxdepth 1 limits the search to the current directory only.
  • -maxdepth 2 allows searching in the current directory and its immediate subdirectories.
  • -name "*.txt" specifies the pattern to match files.

Using the -maxdepth option helps you control how deep the find command will search, making it more efficient and focused on your needs. Let me know if you have any more questions!

0 Comments

no data
Be the first to share your comment!