$linuxjunkies
>

xargs(1)

Build and execute commands from standard input, passing lines as arguments.

UbuntuDebianFedoraArch

Synopsis

xargs [OPTION]... [COMMAND [INITIAL-ARGS]...]

Description

xargs reads items from standard input, separated by blanks or newlines, and executes a command with those items as arguments. This is useful for converting stream data into command arguments, especially when piping output from commands like find that produce one item per line.

By default, xargs passes items as trailing arguments to the command. If no command is specified, echo is used. The command is run as many times as needed to consume all input items.

Common options

FlagWhat it does
-0Use null character (\0) as delimiter instead of spaces/newlines; safe for filenames with spaces
-n NUMPass at most NUM arguments to each command invocation
-I REPLACEReplace REPLACE string with each input item; allows positioning arguments anywhere
-pPrompt user for confirmation before executing each command
-tPrint the command line to stderr before executing it
-xExit immediately if a command fails or would exceed system limits
-P NUMRun up to NUM command processes in parallel
-d DELIMUse DELIM as the item delimiter instead of whitespace
-s SIZELimit command line to SIZE characters (default ~128KB)
-rDo not run command if there is no input

Examples

Find all .log files in /tmp and delete them by passing them to rm

find /tmp -name '*.log' | xargs rm

Search for 'pattern' in files, safely handling filenames with spaces using null delimiters

find . -type f -print0 | xargs -0 grep 'pattern'

Count lines in multiple files, running wc once per file (-n1)

echo -e 'file1\nfile2\nfile3' | xargs -n1 wc -l

Copy each .txt file to a .txt.backup using {} as placeholder for each filename

ls *.txt | xargs -I {} cp {} {}.backup

Fetch 10 URLs in parallel (4 at a time) using -P for parallel execution

seq 1 10 | xargs -P 4 -I {} curl -s 'http://api.example.com/item/{}'

Interactively delete files listed in file_list.txt, prompting before each deletion

xargs -p -n1 rm < file_list.txt

Download URLs from a file, with -t showing each wget command before execution

cat urls.txt | xargs -t wget

Safely handle empty input with -r flag (no command executed if input is empty)

xargs -r bash -c 'echo "Total: $#"' _ < /dev/null

Related commands