Menu
CoddyTech

Batch Work With xargs

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 23 of 39.

xargs reads words from its input and passes them to a command as arguments. It turns a list of paths into one command that works on all of them.

find . -name '*.tmp' -print0 | xargs -0 rm

This deletes every .tmp file below the current folder. Plain xargs splits its input at every space, so old draft.tmp would become two names that do not exist. -print0 makes find end each path with a null character, and xargs -0 splits only there.

echo red green blue | xargs -n 1 echo color:

-n 1 passes one argument per command, so this prints color: red, color: green and color: blue on three lines.

ls *.csv | xargs -I {} cp {} {}.bak

-I {} runs the command once per input line and puts the line wherever {} stands. With jan.csv and feb.csv, this creates jan.csv.bak and feb.csv.bak.

challenge icon

Challenge

Medium

Finish a script that backs up the text files under a folder and counts their lines.

  1. Open backup.sh. It already empties the backup folder. The folder to back up is its first argument.
  2. Copy every file under that folder whose name ends in .txt into backup/, with find -print0 piped into xargs -0 -I {}. File names may contain spaces.
  3. Print Copied:, then the output of ls backup.
  4. Print Lines: N, where N is the total number of lines in those .txt files (xargs -0 cat piped into wc -l).
  5. Save the file.

Try it: run bash backup.sh docs. It prints:

Copied:
2024.txt
report.txt
todo.txt
Lines: 6

Then run bash backup.sh docs/old: it prints Copied:, 2024.txt and Lines: 1.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground