Efficiently build file lists with find and execute commands in bulk with xargs. 16.11.2025 | reading time: 3 min On the command line, `find` discovers files and `xargs` turns lists into commands; together they let you act on thousands of files without writing a loop, saving time and avoiding errors. Real task: remove old logs A safe way to test and then delete log files older than 30 days using a NUL-separated pipeline to handle spaces: ``` find /var/log/myapp -type f -name '*.log' -mtime +30 -print0 | xargs -0 -r echo rm -v -- ``` The previous line shows a dry-run that prints `rm` commands; to actually delete, run: ``` find /var/log/myapp -type f -name '*.log' -mtime +30 -print0 | xargs -0 -r rm -v -- ``` Sample output when files are removed might look like: ``` removed '/var/log/myapp/app 2024-01-01.log' removed '/var/log/myapp/old.log' ``` Handle spaces, newlines and speed Always prefer `-print0` with `xargs -0` for arbitrary filenames; limit arguments per invocation with `-n` and run multiple processes with `-P` to parallelize CPU-bound work, for example: ``` find . -name '*.txt' -print0 | xargs -0 -n1 -P4 gzip ``` Use `-I {}` when the command needs a placeholder, e.g. `xargs -I {} mv {} /tmp/`. Alternatives and when to use them `find -exec ... {} +` behaves like xargs by batching arguments and is portable; use GNU `parallel` when you need advanced job control or complex replacements; prefer xargs for simple, fast batching in shell scripts. Common pitfalls and safety tips Avoid surprises by doing a dry-run with `echo`, stop option parsing with `--` for commands that accept it (for example `rm --`), and note that some `xargs` implementations support `-r` or `--no-run-if-empty` to skip running the command if there are no input items. Next steps for practice Try combining `find` with `xargs` to copy, compress or checksum files; practice on a test directory until the pattern-behavior and separators are second nature; experiment with `-n`, `-P` and `-I` to see how batching and parallelism change runtime. Final thought: mastering `find` plus `xargs` turns many ad-hoc tasks into reliable scripts, and that skill pays off in system administration and automation; learn more about Linux and consider formal credentials like CompTIA Linux+ or LPIC-1 with intensive exam preparation at bitsandbytes.academy. Join Bits & Bytes Academy First class LINUX exam preparation. utilities filesystem scripting