xargs

prefer splitting by null char

Normally xargs processes input line by line, this is not the most robust option it is more robust to split on null character, eg:

find ./ -print0 | xargs -0 stat 

Single positional argument

Here we use a space as a seperator, notice in the output the 4th line were xargs also takes the \n into consideration. Leaving this example here as a warning.

echo 'een twee drie vier' | xargs -d ' ' -I {} echo "I received: {} as input."
# Output: 
# I received: een as input.
# I received: twee as input.
# I received: drie as input.
# I received: vier
#  as input.

Multiple positional arguments

-n 2 instructs xargs to split the input in parts of <=2 and invoke command with max 2 arguments. By default xargs uses the input as an unlimited list of arguments.

NOTE: when -n <number> is used, positional arguments are not possible anymore. This because the replacement chars given by -I can not reference a specific argument. Eg there is no such thing as $1 $2 in xargs.

echo "een twee drie vier" | xargs -n 2 sh -c 'echo "first: $1 second: $2"' _

# Output:
# first: een second: twee
# first: drie second: vier

Rudimentary threading

Watch out for sharing resources among the different threads:

for i in {1..20}; do echo $i; done | \
    xargs -P 3 --process-slot-var=ID -I {} sh -c \
        'echo "[$ID] This was line nr: {}."; sleep 1'

# Output:
# [0] This was line nr: 1.
# [1] This was line nr: 2.
# [2] This was line nr: 3.
# [0] This was line nr: 4.
# [1] This was line nr: 5.
# [2] This was line nr: 6.
# [0] This was line nr: 7.
# [1] This was line nr: 8.
# ...

Handy dandy options