0
0
Linux CLIscripting~5 mins

xargs for building commands from input in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you have a list of items and want to run a command on each one. Typing each command manually is slow. xargs helps by taking input and building commands automatically to run them efficiently.
When you have a list of filenames and want to delete them all at once.
When you want to search for a word in many files listed by another command.
When you want to copy multiple files whose names come from a text list.
When you want to run a command on each line of output from another command.
When you want to speed up commands by running many items in parallel.
Commands
This command deletes the files named file1.txt, file2.txt, and file3.txt by passing them as arguments to rm using xargs.
Terminal
echo 'file1.txt file2.txt file3.txt' | xargs rm
Expected OutputExpected
No output (command runs silently)
This lists all .log files and searches for the word 'error' inside them by passing the filenames to grep using xargs.
Terminal
ls *.log | xargs grep 'error'
Expected OutputExpected
server.log:error: failed to start app.log:error: connection lost
This reads filenames from files.txt and prints each one on its own line by running echo once per filename (-n 1).
Terminal
cat files.txt | xargs -n 1 echo
Expected OutputExpected
file1.txt file2.txt file3.txt
-n 1 - Run the command once per input item
This finds all .tmp files in /tmp and deletes them. The -r flag prevents running rm if no files are found.
Terminal
find /tmp -type f -name '*.tmp' | xargs -r rm
Expected OutputExpected
No output (command runs silently)
-r - Do not run command if no input
Key Concept

If you remember nothing else from this pattern, remember: xargs builds and runs commands from input lists to automate repetitive tasks efficiently.

Common Mistakes
Using xargs without quotes when input items contain spaces
xargs splits input on spaces, so filenames with spaces get broken into parts causing errors
Use null-terminated input with find -print0 and xargs -0 to handle spaces safely
Running xargs without checking if input is empty
Commands like rm run with no arguments and may cause errors or unexpected behavior
Use the -r flag to prevent running the command if there is no input
Summary
xargs reads input and builds commands to run on each item automatically.
Use flags like -n to control how many items per command and -r to avoid running commands with empty input.
Always be careful with input containing spaces and use -0 with null-terminated input to handle them safely.