AI Hints
Home›Linux Tutorial›Exit Codes, diff, xargs
Linux · Lesson 57 of 120

xargs

Turn a list into arguments.

⏱ 2 min read▶ Video at 1:13:35🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Some commands don't read from a pipe. RM, MK dir, and touch want names as arguments, not as input. Xargs builds a bridge. It takes a list from a pipe, and turns it into arguments.

xargs
From the video: xargs
  • Some commands ignore pipes
  • They want arguments
  • xargs builds the bridge

From a list to arguments

Here's a file with three folder names. Cat prints them. Piping them straight into MK dir wouldn't work. But through xargs, MK dir receives all three names as arguments, and creates them.

Terminal
cat months.txt
jan
feb
mar
cat months.txt | xargs mkdir
ls -d jan feb mar
feb  jan  mar

With find

Xargs is often used with find. Here, find lists every log file in our home, and xargs passes them all to WC dash L, which counts the lines in each. One command, run on many files.

Terminal
find . -name "*.log" | xargs wc -l
  60 ./logs/old.log
  60 ./logs/server.log
 120 total

Careful with spaces

Remember the trouble with spaces in names? Xargs splits on spaces too. So a file called my notes would become two arguments. The safe version is find dash print zero, with xargs dash zero. And for deleting, find's own dash delete is usually simplest.

keyvalue
cmd | xargs cmd2list to arguments
find | xargsact on many files
Spacescan break names
Safefind -print0 | xargs -0

Summary

Xargs turns lines from a pipe into arguments, for commands that don't read input. Next, simple patterns, for smarter searches.

Key takeaways
  • ... | xargs cmd
  • Great with find
  • -print0 / -0 for spaces
Next up: Simple Patterns — ^ $ and . in grep