xargs—constructs an argument list(s) and executes a command

xargs [ flags ] [ command [ initial–arguments ] ]

xargs allows you to transfer contents of files into a command line and dynamically build command lines. (See Linux man page for a long listing of all options.)

Example A.72.
1  ls $1 | xargs -i -t mv $1/{} $2/{}
2  ls | xargs -p -l rm -rf
3  find . -type f | xargs grep -l "ellie"
				

Explanation

  1. Moves all files from directory $1 to directory $2, and echos each mv command just before executing.

  2. Prompts ( -p) the user with files that are to be removed, one at a time, and removes each one.

  3. The find command starts searching the current directory for plain files, and sends the list of files to xargs. xargs transfers the filenames to grep.

Get Linux Shells by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.