Bash Index : X - The 'X' Bash commands : description, flags and examples




Construct argument lists and invoke utility : xargs options utility

xargs may return exit codes such as 123, 124, 125, 126 or 127 if something went wrong when calling 'utility' (for details : ).

By default, xargs reads newline-separated input values.


Flag Usage
-I pattern Replace pattern with values piped into xargs (example)
-n n Pop n arguments at a time from the list to feed utility
-P n Execute at most n parallel instances of utility. Defaults to 1. (source).
-n should be specified when using -P or there is a risk of firing only 1 instance of utility.


tar all files of the current directory :

find -maxdepth 1 -type f | xargs tar cf archive.tar

Download all URLs listed in a file (source) :

cat urlList.txt | xargs wget -c
This example, albeit quite functional, is actually deprecated by wget's -i.

Archive the n latest files matching pattern :

ls -t *pattern* | head -n n | xargs tar cfz /path/to/archive.tgz

Cannot umount a filesystem because of open files ? Kill, kill, KILL !!! :

Killing so many processes this way is VERY! BAD!. Do this only if :

  • these processes are started at boot time
  • AND you can not switch to a lower runlevel
  • AND you can not stop them all
  • AND you plan to reboot shortly
  • AND (many other reasons to convince you this is a bad thing )

lsof /mnt/myFilesystem | awk '{print $2}' | sed '1d' | xargs kill -15

How to use the values piped to xargs into its sub-command ?

for i in {1..5}; do echo $i; done | xargs -I pattern echo 'this is line pattern.'

Looks like xargs substitutions have precedence over Bash.
To use values more than once :

for i in {a..e}; do echo $i; done | xargs -I whatIWant sh -c 'echo -n "I can say \"whatIWant\"."; echo " And I can say it even louder : \"$(echo whatIWant | tr '[:lower:]' '[:upper:]') !\""'

sh -c 'someCommand' above means "run someCommand within the /bin/sh shell". Some "advanced" commands / flags / options may not be available in this shell. Consider bash -c 'someCommand' then.