ubuntu, updated

xargs: run a command for many items

A beginner-friendly explanation of xargs: turn a list of files, users or hosts into command arguments, safely and in parallel.

The problem xargs solves

Many commands produce a list (files from find, names from grep -l, lines in a file). Many other commands want their input as arguments (rm file1 file2, chmod +x a b c). A pipe alone doesn’t connect them:

find . -name "*.tmp" | rm          # does NOT work: rm ignores its input
find . -name "*.tmp" | xargs rm    # works

xargs reads lines from its input and adds them as arguments to a command.

flowchart LR
    A["find ...
a.tmp
b.tmp
c.tmp"] -->|pipe| X["xargs rm"] X --> R["rm a.tmp b.tmp c.tmp"]

See what it would do first

Put echo in front of the command. xargs then prints the command instead of running it:

find /var/log -name "*.gz" -mtime +30 | xargs echo rm
# rm /var/log/syslog.5.gz /var/log/auth.log.4.gz ...

Or use -p to confirm each run, or -t to print each command before it runs.

The options you need

OptionDoesExample
(none)Put as many items as possible behind the commandcat files.txt | xargs rm
-n 1One item per command runxargs -n 1 ping -c1
-I {}Put each item where {} is, one run per itemxargs -I {} cp {} /backup/
-0Items are separated by a null byte (safe for spaces), use with find -print0find . -print0 | xargs -0 rm
-d '\n'Split only at line ends (so spaces in names are kept)xargs -d '\n' rm
-P 4Run up to 4 commands in parallelxargs -P 4 -n 1 gzip
-rDon’t run the command if the input is emptyxargs -r rm
-tPrint each command before running itxargs -t rm
-pAsk before each commandxargs -p rm

The space problem

By default xargs splits at spaces and newlines. A file called my report.txt becomes two arguments, my and report.txt, and rm deletes the wrong things or fails.

Always use one of these for file names:

find . -name "*.log" -print0 | xargs -0 rm           # best: null-separated
grep -rlZ "oldhost" /etc/app | xargs -0 sed -i 's/oldhost/newhost/g'   # grep -Z = null-separated
ls | xargs -d '\n' echo                              # split at line ends only

xargs or find -exec?

find can run commands itself:

find . -name "*.tmp" -exec rm {} +       # like xargs: many files per rm
find . -name "*.tmp" -delete             # even simpler for deleting

Use find -exec when the list comes from find anyway. Use xargs when the list comes from anywhere else (a file, grep, awk, another command), or when you want parallel runs with -P.

Next: xargs snippets.

§ home
~/knubertus/home/
1,1 Top