Introduction
In the Linux environment, the ability to combine commands via pipes is one of the most powerful features of the shell. However, sometimes we need to take the output of a command and use it as arguments for another command that does not accept standard input directly. This is where xargs comes in, a tool that builds and executes commands from data read from stdin.
What is xargs?
xargs reads whitespace-separated items (spaces, tabs, or newlines) from standard input and converts them into arguments for the command that is specified. Its basic operation is: command1 | xargs command2. In this way, command2 receives each item as a separate argument, allowing processing of file lists, paths, or any other type of data.
Basic Syntax
The simplest form is:
xargs [options] [command [arguments]]
If no command is specified, xargs runs /bin/echo by default, displaying the arguments read.
Practical Examples
- Delete files listed by
find:find /tmp -name "*.tmp" -print0 | xargs -0 rm -f - Compress several logs:
ls *.log | xargs gzip - Change permissions on a list of directories:
cat dirs.txt | xargs chmod 755
Usage with find and the null separator
When file names may contain spaces or newlines, using the null character as a separator prevents xargs from misinterpreting them. The combination of -print0 from find and the -0 option of xargs ensures safe handling:
find . -type f -name "*.bak" -print0 | xargs -0 rm -f
Usage with grep and recursive search
Suppose we want to search for a word in all files of a directory and then display only the names of the files that contain matches:
grep -rl "error" /var/log | xargs -I {} cp {} /backup/
In this example, the -I {} option tells xargs to replace the string {} with each item read, allowing the file name to be used in any position of the command.
Handling spaces and special characters
By default, xargs treats any whitespace as a separator. If the data contains internal spaces, quotes or the null delimiter can be used as shown earlier. Another alternative is to change the delimiter with the -d option:
echo "file one,file two,file three" | xargs -d ',' rm -f
Useful Options
-n N: passes at most N arguments per command invocation.-P N: runs up to N processes in parallel, speeding up tasks such as compression or download.-t: prints the command that is about to be executed before running it (verbose mode).-r: prevents xargs from running the command if the input is empty.-I replacement: defines a replacement string for using the arguments anywhere in the command.
Comparison with while read loops
A common alternative to xargs is to read the input with a while read loop and
This post is also available in ESPAÑOL.