Bash Xargs
Xargs is a command that builds new commands from lines of input. It takes words from standard input and places them as arguments to another command.
One placeholder per input item
The -I {} flag puts each input word into the echo command. Each word gets its own line of output.
printf '%s\n' alpha beta gamma | xargs -I {} echo "hello {}"Two items per command run
The -n 2 flag groups the input into pairs. Each pair is printed on one line.
printf '%s\n' one two three four | xargs -n 2 echoFile names with spaces stay whole
Find prints null-separated names, and xargs -0 reads them that way. Each name keeps its space, and sort puts the list in order.
touch "red apple.txt" "green pear.txt"
find . -maxdepth 1 -type f -name '*.txt' -print0 | xargs -0 -n 1 basename | sortExample
printf '3\n1\n2\n' | xargs -P 3 -I {} sh -c 'echo "task {} done"' | sortKey points
- xargs: a command that turns input lines into arguments for another command.
- -I {}: a placeholder that marks where each input item goes in the command.
- -n 2: a limit that passes at most two items to each run of the command.
- -0: a flag that splits input on null bytes instead of spaces.
- -P 3: a flag that runs up to three commands at the same time.
- Use -0 with find -print0 so file names with spaces stay whole.
In this example, printf feeds the numbers 3, 1, and 2 to xargs. The -P 3 flag lets up to three commands run at the same time. The -I {} flag puts each number into its own echo command. Sorting the collected output puts the lines in number order, so parallel runs still print a fixed result.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why pair find -print0 with xargs -0?