#!/bin/bash
#
# 'xargs' builds a list of arguments from stdin and executes a command with
# that list of arguments.
# This can be used when you need use the output from a command and as an
# argument to another.
# A pipe cannot be used in this case, since it takes the output from one
# command and sends it to the input stream of another.
#
# The command is run multiple times, once per line of arguments, until
# stdin is exhausted.
# Many options to specify maximum number of arguments, separators, etc.
#
# By default, the input is appended to the end of the command as a list of
# arguments.
# It can be inserted anywhere using a placeholder (the traditional
# placeholder is {}).
#
# Example:
# (You don't need 'xargs' for this example, but it illustrates it.)

echo "ls -l" | xargs bash -c

# Example: find out all the .txt files and archive them using tar

directory="/tmp/foo"
find "$directory" -name "*.txt" -type f -print0 | xargs -0 tar -cvzf textfiles.tar.gz

# In my experience, xargs can almost always be replace by another option.
# Where it truly shines is when you need to run a command multiple times
# over a list of arguments.
