Tuesday, October 30, 2012

The XARGS command


The xargs Command.


Xargs' power lies in the fact that it can take the output of one command, and use that output as arguments to another command. So, using the basic find command below, let us pass the output of find to xargs and get xargs to issue multiple 'ls -l' commands.

# find ~ -type f -mmin -90 | xargs ls -l

The sample output would then become    
-rw-rw-r--    1 linux    lunux    10209032 Jun 30 13:28 /home/linux/dns/mysql-outfile/dnsx.doc
-rw-rw-rw-    1 mysql    mysql    10209032 Jun 30 12:53 /home/linux/dns/mysql-outfile/dnsx.txt

Important Switches

-r --> Tells xargs to quit; when the its i/p doesn't contain any non-zero files.
# find ~ -type f -mtime +1825 |xargs -r ls -l

-0, --null --> Expect filenames to be terminated by NULL instead of whitespace. Do not treat quotes or backslashes specially.
Used with print0 command (at first set), so the args are terminated with a null.

$ find /share/media/mp3/ -type f -name "*.mp3" -print0 | xargs -0 -r -I {} cp -v -p {} --target-directory=/bakup/iscsi/mp3/

-n args, --max-args=args --> Max number or args to pass to the 2nd command at a time.
$ echo 1 2 3 4 | xargs -n 2

-I [string] --> Replace all occurrences of { }, or string, with the names read from standard input. Unquoted blanks are not considered argument terminators. Implies -x and -L 1.

-L [lines] , --max-lines[=lines] --> Allow no more than lines nonblank input lines on the command line (default is 1). Implies -x.
-x, --exit --> If the maximum size (as specified by -s) is exceeded, exit.
-s max, --max-chars=max --> Allow no more than max characters per command line.