LinuxCommandLibrary

xargs

TLDR

Run command with arguments from stdin

$ echo [file1 file2] | xargs rm
copy
Use custom delimiter
$ echo "[a:b:c]" | xargs -d ":" echo
copy
Run with placeholder
$ find . -name "*.txt" | xargs -I {} cp {} [/backup/]
copy
Run in parallel
$ find . -name "*.jpg" | xargs -P [4] -I {} convert {} {}.png
copy
Handle filenames with spaces
$ find . -name "*.txt" -print0 | xargs -0 rm
copy
Limit arguments per command
$ echo {1..100} | xargs -n [10] echo
copy
Prompt before execution
$ find . -name "*.tmp" | xargs -p rm
copy
Run even with empty input
$ echo "" | xargs -r echo "not empty"
copy

SYNOPSIS

xargs [-I replace] [-n max-args] [-P max-procs] [-0] [-d delim] [command]

DESCRIPTION

xargs builds and executes commands from standard input. It converts input into arguments for a command, handling batching, parallelization, and argument limits.
By default, xargs appends all input as arguments to a single command invocation. The -n option limits arguments per invocation, running the command multiple times.
The -I flag enables argument placement anywhere in the command. {} (or any placeholder) is replaced with each input item. This runs the command once per input item.
Parallel execution (-P) runs multiple commands simultaneously. Combined with -n or -I, this processes items concurrently, utilizing multiple CPU cores.
Null-delimited input (-0) handles filenames with spaces, newlines, or special characters safely. Use with find -print0 or similar tools.
Without -r, xargs runs the command even with empty input. The -r flag prevents this, useful when empty input would cause errors.

PARAMETERS

-I REPLACE

Replace string in command.
-n NUM, --max-args NUM
Maximum arguments per command.
-P NUM, --max-procs NUM
Parallel processes.
-0, --null
Input items are null-terminated.
-d DELIM, --delimiter DELIM
Input delimiter character.
-p, --interactive
Prompt before each execution.
-t, --verbose
Print commands before execution.
-r, --no-run-if-empty
Don't run if input is empty.
-L NUM, --max-lines NUM
Use NUM lines per command.
-s NUM, --max-chars NUM
Maximum command line length.
-a FILE, --arg-file FILE
Read arguments from file.
-x, --exit
Exit if command line too long.
--show-limits
Show system limits.

CAVEATS

Special characters in filenames cause issues without -0. Shell features (pipes, redirects) need wrapper scripts. Argument limit depends on system. Error handling across parallel jobs is limited. Order not preserved with -P.

HISTORY

xargs originated in PWB/UNIX in the 1970s. It addressed the limitation of shell command line length - programs couldn't accept unlimited arguments. The tool became essential for chaining Unix commands, enabling "do something to many files" patterns that define Unix philosophy.

SEE ALSO

find(1), parallel(1), apply(1)

Copied to clipboard