xargs Notes

Useful Options

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#-n max-args, --max-args=max-args
# Use at most max-args arguments per command line.
find . | xargs -n1 echo

#-I replace-str
find . | xargs -n1 -I% echo % suffix

#-P max-procs, --max-procs=max-procs
# Run up to max-procs processes at a time; the default is 1.
find . | xargs -P10 -n1 -I% sleep 1

#-0, --null
# Input items are terminated by a null character instead of by whitespace.
find . -type f -name "*.java" -print0 |xargs -0 grep -li "keyword"

#-p, --interactive
# Prompt the user about whether to run each command line and read a line from the terminal. Implies -t.
find . | xargs -p -n1 echo

#-t, --verbose
# Print the command line on the standard error output before executing it.

#--delimiter=delim, -d delim
# Input items are terminated by the specified character.

#-a file, --arg-file=file
# Read items from file instead of standard input.

Tricks

Execute Shell Scripts

1
2
3
4
5
6
# The word bash at the end of the line is interpreted by bash
# -c as special parameter $0.
# The single quote ' is critical, otherwise $filename will be
# replaced before the script is executed.
find /path -type f -name '*~' -print0 | xargs -0 bash -c \
'for filename; do cp -a "$filename" ~/backups; done' bash

Prevent xargs from Quitting on Error

1
2
# instead echo the commands and pipe to bash, echo will not return error
find . | xargs -n1 echo command_that_might_exit | bash

Reference

xargs - Wikipedia
prevent xargs from quitting on error