Linux organizes countless files within its directory structure. To search and manage them efficiently, tools like locate
, find
, xargs
, touch
, and stat
are invaluable. This guide introduces their capabilities and practical use cases.
locate
quickly searches file paths using a pre-built database:
locate bin/zip
Combine with grep
for filtering:
locate zip | grep bin
The database may not reflect recent files. To refresh it manually:
sudo updatedb
find
searches directories recursively based on attributes:
find ~ | wc -l
find ~ -type d | wc -l
find ~ -type f | wc -l
Type | Description |
---|---|
b | Block device |
c | Character device |
d | Directory |
f | Regular file |
l | Symbolic link |
find ~ -type f -name "*.JPG" -size +1M | wc -l
Unit | Description |
---|---|
b | 512-byte blocks |
c | Bytes |
w | 2-byte words |
k | Kilobytes |
M | Megabytes |
G | Gigabytes |
Test | Description |
---|---|
-cmin | Files modified n minutes ago |
-cnewer | Newer than reference file |
-empty | Empty files or directories |
-name | Matches filename pattern |
-iname | Case-insensitive pattern |
-user | Owned by specific user |
find ~ \( -type f -not -perm 0600 \) -or \( -type d -not -perm 0700 \)
Operator | Function |
---|---|
-and / -a | Both conditions must be true |
-or / -o | Either condition is true |
-not / ! | Negates a condition |
() | Groups conditions (escaped with \) |
Action | Description |
---|---|
-delete | Removes matching files |
-ls | Displays details via ls -dils |
Prints full file path | |
-quit | Stops after first match |
find ~ -type f -name '*.bak' -delete
find ~ -type f -name 'foo*' -exec ls -l '{}' ';'
find ~ -type f -name 'foo*' -ok ls -l '{}' ';'
find ~ -type f -name 'foo*' -exec ls -l '{}' +
find ~ -type f -name 'foo*' -print | xargs ls -l
find ~ -iname '*.jpg' -print0 | xargs --null ls -l
mkdir -p playground/dir-{001..100}
touch playground/dir-{001..100}/file-{A..Z}
find playground -type f -name 'file-A' | wc -l
touch playground/timestamp
stat playground/timestamp
find playground -type f -name 'file-B' -exec touch '{}' ';'
find playground -type f -newer playground/timestamp
find playground \( -type f -not -perm 0600 -exec chmod 0600 '{}' ';' \) -or \( -type d -not -perm 0700 -exec chmod 0700 '{}' ';' \)
Option | Description |
---|---|
-depth | Process files before their parent directories |
-maxdepth | Limits how deep find descends |
-mindepth | Skips initial levels before applying tests |
-mount | Prevents crossing into other filesystems |
-noleaf | Disables UNIX filesystem optimization |
loc