Bash xargs Command - Build Commands from Input
Using the xargs Command
Some commands, like rm, touch and echo, do not read from a pipe. They need their arguments on the command line.
The xargs command solves this. It reads items from its input and adds them as arguments to another command.
The examples below use this file, names.txt:
Liam
Emma
Noah
Basic Usage
Here, xargs reads the three names and runs echo once with all of them:
Example: Pass Lines as Arguments
cat names.txt | xargs echo Hello
Hello Liam Emma Noah
This is the same as typing echo Hello Liam Emma Noah.
One Item at a Time (-n)
Use -n 1 to run the command once for each item:
Example: Run Once per Line
cat names.txt | xargs -n 1 echo Hello
Hello Liam
Hello Emma
Hello Noah
Place the Item Anywhere (-I)
Use -I {} to choose where the item goes in the command. Every {} is replaced by the item:
Example: Create One File per Name
cat names.txt | xargs -I {} touch {}.txt
ls Liam.txt Emma.txt Noah.txt
Emma.txt Liam.txt Noah.txt
Use xargs with find
find and xargs are often used together. This counts the lines of every .sh file in the project folder:
Example: Count Lines in All Scripts
find project -name "*.sh" | xargs wc -l
1 project/scripts/test.sh
1 project/scripts/build.sh
2 total
If file names can contain spaces, use find -print0 with xargs -0. The names are then separated by a special null character instead of spaces:
Ask Before Running (-p)
Use -p to make xargs show each command and ask before running it. Type y to run it:
Example: Confirm Each Command
cat names.txt | xargs -p -n 1 echo
echo Liam?...y
Liam