Building commands with xargs
- Version
- unversioned
- Review
- Draft
Summary#
xargs reads items from standard input and appends them as arguments to a command. It runs echo when you do not name a command.
Syntax#
find directory -type f -print0 | xargs -0 -r command
printf '%s\n' item | xargs -n 1 command
printf '%s\n' item | xargs -I NAME command NAME
-n limits the number of arguments per run. -I runs the command once per input line and substitutes the line for the placeholder.
Example#
(
set -eu
export LC_ALL=C
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
: > 'first draft.txt'
: > notes.txt
find . -type f -name '*.txt' -print0 | sort -z | xargs -0 printf '[%s]\n'
echo '-- two arguments per run'
printf '%s\n' a b c | xargs -n 2 echo 'batch:'
echo '-- one run per line'
printf '%s\n' alpha beta | xargs -I NAME echo 'hello NAME'
echo '-- empty input'
printf '' | xargs echo 'ran once'
printf '' | xargs -r echo 'never printed'
echo 'done'
)
Expected output#
[./first draft.txt]
[./notes.txt]
-- two arguments per run
batch: a b
batch: c
-- one run per line
hello alpha
hello beta
-- empty input
ran once
done
Common mistakes#
By default, xargs splits input at blanks and newlines and treats quotes and backslashes specially, so ordinary file names can break apart. Pair find -print0 with xargs -0. GNU xargs also runs the command once for empty input; add -r when the command must not run without arguments.
Version applicability#
This entry describes GNU findutils xargs. The xargs shipped with macOS skips the command on empty input by default.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0