ubuntu, updated
find: locate files
Find files by name, type, age, size, owner and permissions, and run commands on the results.
How it works
find WHERE CONDITIONS ACTION
find /var/log -name "*.log" -mtime +7 -delete
find walks through every folder below WHERE and checks each file against the conditions. Without an action it prints the paths. Several conditions mean AND.
By name and type
| What | Command |
|---|---|
| By name (exact, case-sensitive) | find /etc -name "hosts" |
| By pattern (quote it!) | find /etc -name "*.conf" |
| Ignore case | find / -iname "readme*" |
| Only files / only directories | -type f / -type d |
| Only symlinks | -type l |
| Path contains | find / -path "*nginx*" -name "*.conf" |
| Limit depth | find /etc -maxdepth 1 -name "*.conf" |
| Stay on one file system | find / -xdev -name core |
By age, size, owner, permissions
| What | Command |
|---|---|
| Changed in the last 24 h | -mtime -1 |
| Older than 30 days | -mtime +30 |
| Changed in the last 15 minutes | -mmin -15 |
| Newer than a reference file | -newer /etc/passwd |
| Bigger than 1 GB | -size +1G |
| Smaller than 10 KB | -size -10k |
| Empty files or dirs | -empty |
| Owned by a user / group | -user anna / -group developers |
| Owner no longer exists | -nouser |
| Exact permissions | -perm 777 |
| World-writable | -perm -o+w |
| setuid files | -perm -4000 |
-mtime +30 means “more than 30 days ago”, -30 means “within the last 30 days”.
OR, NOT, exclude
find . -name "*.log" -o -name "*.gz" # OR
find . -type f ! -name "*.conf" # NOT
find / -path /proc -prune -o -name "*.pem" -print # skip /proc completely
Actions
| What | Command |
|---|---|
Print with details (like ls -l) | -ls |
| Delete (test without it first!) | -delete |
| Run a command per file | -exec chmod 640 {} \; |
| Run a command with many files at once (faster) | -exec chmod 640 {} + |
| Ask before each | -ok rm {} \; |
| Null-separated output for xargs | -print0 (see xargs) |
Snippets
# Biggest files on the root file system
sudo find / -xdev -type f -size +500M -exec ls -lh {} + 2>/dev/null
# Files changed in /etc today (what did someone change?)
sudo find /etc -type f -mtime -1
# Delete logs older than 14 days
sudo find /var/log/app -name "*.log" -mtime +14 -delete
# Fix permissions: dirs 755, files 644
find /srv/www -type d -exec chmod 755 {} +
find /srv/www -type f -exec chmod 644 {} +
# Empty directories
find /srv/data -type d -empty
# Files owned by a deleted user
sudo find / -xdev -nouser 2>/dev/null
2>/dev/null hides the “Permission denied” noise.
Faster: locate
locate searches a prebuilt index, so it answers instantly, but only knows files that existed at the last (daily) index run.
sudo apt install plocate
locate nginx.conf
sudo updatedb # refresh the index now