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

Sample output: 
-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.


Most used while deleting/copying a large number of files which can't by default, handled by rm or cp or any other commands.

Xargs examples.

# ls |xargs -I {} cp -v {} /mnt/import_log/


The above command will copy all the files from the current location to /mnt/import_log/ irrespective of number of files.


# ls |xargs -n10 -I {} tar -cvf /mnt/import_log_file.tar {}

The above command will tar the entire contents of the current directory to /mnt/import_log_file.tar.


Similarly you will find the xargs command to be useful in many cases.

An example error if you try to delete contents a directory with a lot of files.

/bin/rm: Argument list too long.

Just use the xargs as above to solve this.