Skip to content

find -exec and xargs: act on every file you find

AdvancedLesson 37 of 669 min

Compress old logs with find -mtime and -exec, delete temp files, and search the rest with xargs, safely with names that have spaces. Practise in your browser.

A server's logs folder grows every day. The usual clean-up: compress the logs older than a week, delete the temporary files, and check which recent logs mention an error. find already lists files by name; it can also pick them by age, and run a command on each one.

ls -l logs

Picking files by age and size

-mtime +7 means changed more than 7 days ago, -mtime -2 less than 2 days ago. -size +10M finds files bigger than 10 MB.

find logs -name "*.log" -mtime +7

-exec: run a command on each file

-exec runs a command once for every path found, with {} replaced by the path. The command ends with \;: the backslash keeps the shell from taking the ; for itself.

find logs -name "*.log" -mtime +7 -exec ls -l {} \;

End with {} + instead and find runs the command once with all the paths, which is quicker for many files: find logs -name "*.log" -exec wc -l {} +.

-delete is built in for the most common job:

find logs -name "*.tmp" -delete

Careful:Run find without -exec or -delete first and read the list. There's no undo, and a test in the wrong place (or a missing one) matches more than you meant.

xargs: turn a list into arguments

xargs reads a list of words and adds them to the end of a command. Piped from find, it runs one command for the whole list:

find logs -name "*.log" | xargs grep -l ERROR

That breaks on monthly report.log: xargs splits its input at spaces, so grep gets logs/monthly and report.log. The safe pair is find -print0, which ends each name with an invisible NUL byte, and xargs -0, which splits only there:

find logs -name "*.log" -print0 | xargs -0 grep -l ERROR

-exec grep -l ERROR {} + gets the same answer, since find never splits names.

Your turn

Clean up logs: (1) compress every .log file older than 7 days with gzip (it makes name.log.gz), leaving the newer ones alone; (2) delete every .tmp file under logs; (3) list the log files that contain ERROR, the monthly report included.

Next