Skip to content

Basic usage of find command in Linux

homepage-banner

Common file search commands in Linux: locate, find, ag.

Introduction

In Linux, the find command is used to search for files and directories in a specified directory hierarchy. It is a powerful tool that can locate files based on various criteria such as name, size, type, and modification time.

locate

Simple to use, searches based on database, not real-time. Usage:

locate FILENAME

Manually update database (may take some time):

updatedb

find

Real-time, precise, powerful. Usage:

find PATH SEARCH_STANDARD SEARCH_ACTION

(1) PATH: “.” or “./” both represent current directory

(2) SEARCH_STANDARD:

-name 'FILENAME'    Exact filename match (supports wildcard * ? [])
-iname 'FILENAME'   Fuzzy filename match (case-insensitive)
-regex PATTERN      Regular expression match
-user USERNAME    Search based on owner
-group GROUP      Search based on group
-uid UID
-gid GID
-nouser           Files without owners
-type    Search based on file type
-type f  File
-type d  Directory
-type c  Character device
-type b  Block device
-type l  Link
-type p  Pipe
-type s  Socket
-size         Search based on file size
-size 10k
-size 25M
-size 3G
-size +10k    Files larger than 10k
-size -5M     Files smaller than 5M

Combination options:

-a     AND
-o     OR
-not   NOT

Search based on time:

-mtime    modified time (default unit: days)
-ctime    change time
-atime    access time

-ctime +5     Changed over 5 days ago
-access -3    Accessed within the last 3 days

-mmin    (default unit: minutes)
-cmin
-amin

Search based on permissions:

-perm 755    Exact permission
-perm /644    Any of the three digits match
-perm -700    Includes 600/500/.../000

Example 1: Find all regular files without owners in /tmp

find /tmp -nouser -a -type d

Example 2: Find files in /etc that are neither regular files nor directories

find /etc -not \( -type d -o -type f \)

(3) SEARCH_ACTION:

-print    Default action
-ls       List
-ok COMMAND \;    Requires confirmation to execute COMMAND
-exec COMMAND \;  Executes COMMAND without confirmation

Example 3: Find all files in current directory with permission 600 and display their sizes ({} represents found files, \; represents end)

find . -perm 600 -exec du {} \;

Example 4: Find all files in current directory with permission 400 and add “.new” to their filenames

find ./ -perm 400 -exec mv {} {}.new \;

Conclusion

The find command is a powerful tool for searching for files and directories in Linux. With its advanced search criteria and ability to execute commands on each file found, it can be an invaluable tool for managing large file systems.

Leave a message