Xargs

Xargs

xargs(pronounced zargs) is a command of Unix and most Unix-like operating systems. It is useful when one wants to pass a large number of arguments to a command. Arbitrarily long lists of parameters can't be passed to a command, [ [http://www.gnu.org/software/coreutils/faq/coreutils-faq.html#Argument-list-too-long GNU Core Utilities FAQ] ] so xargs will break the list of arguments into sublists small enough to be acceptable.

For example, commands like:

rm /path/* rm `find /path -type f`

will fail with an error message of "Argument list too long" if there are too many files in "/path". However this version (functionally equivalent with "rm `find /path -type f`") will not fail:

find /path -type f -print0 | xargs -0 rm

In this example, "find" feeds the input of "xargs" with a long list of file names. "xargs" then splits this list into sublists and calls "rm" once for every sublist. This is more efficient than this functionally equivalent version: find /path -type f -exec rm '{}' ;

which calls "rm" once for every single file. Note however that with modern versions of "find", the following variant does the same thing as the "xargs" version:

find /path -type f -exec rm '{}' +

xargs often covers the same functionality as the backquote feature of many shells, but is more flexible and often also safer, especially if there are blanks or special characters in the input. It is a perfect companion for commands that output long lists of files like find, locate and grep.

Examples

find . -name "*.foo" | xargs grep bar

does the same as

grep bar `find . -name "*.foo"`

Note that the preceding command uses backticks (`), not single quotes ('). It searches in all files in the current directory and its subdirectories which end in .foo for occurrences of the string bar. These commands will not work as expected if there are whitespace characters, including newlines, in the filenames. In order to avoid this limitation one may use:

find . -name "*.foo" -print0 | xargs -0 grep bar

which uses GNU specific extensions to find and xargs to separate filenames using the null character;

find . -name "*.foo" -print0 | xargs -0 -t -r vi

is similar to above, but launches the vi editor for each of the files. The -t prints the command to stderr before issuing it. The -r is a GNU extension that tells xargs not to run the command if no input was received.

find . -name "*.foo" -print0 | xargs -0 -I mv {} /tmp/trash

uses -I to tell xargs to replace {} with the argument list. Note that not all versions of xargs supports the {} syntax. In those cases you may specify a string after -I that will be replaced, e.g.

find . -name "*.foo" -print0 | xargs -0 -I xxx mv xxx /tmp/trash

uses string xxx instead of {} as the argument list marker.

find . -maxdepth 1 -type f -name "*.mp3" -print0 | xargs -0 -r cp -v -p --target-directory=/home/media

does the same as:

cp -v -p *.mp3 /home/media

however, the former command which uses find/xargs/cp is more resource efficient and will not halt with an error if the number of files is too large for the cp command to handle.

References

External links

* [http://unixhelp.ed.ac.uk/CGI/man-cgi?xargs GNU man page on xargs]


Wikimedia Foundation. 2010.

Игры ⚽ Нужна курсовая?

Look at other dictionaries:

  • xargs — утилита для формирования списка аргументов и выполнение команды в UNIX подобных операционных системах. Команда xargs объединяет зафиксированный набор заданных в командной строке начальных аргументов с аргументами, прочитанными со стандартного… …   Википедия

  • Xargs — утилита для формирования списка аргументов и выполнение команды в UNIX‐подобных операционных системах. Команда xargs объединяет зафиксированный набор заданных в командной строке начальных аргументов с аргументами, прочитанными со стандартного… …   Википедия

  • xargs — ● ►en /X argz/ cde. f. ►UNIX Le x est en fait un produit... Cette commande permet de combiner des arguments pour produire une ligne de commande. Exemple: xargs grep pouette < liste Cette commande donnera les lignes contenant le mot pouette… …   Dictionnaire d'informatique francophone

  • The Baseball Network — Infobox Network network name = The Baseball Network name = network network type = Joint venture involving the American Broadcasting Company, the National Broadcasting Company, and Major League Baseball. branding = Baseball Night in America… …   Wikipedia

  • find — find  утилита поиска файлов, используемая в UNIX‐подобных операционных системах. Может производить поиск в одном или нескольких каталогах с использованием критериев, заданных пользователем. По умолчанию, find возвращает все файлы в рабочей… …   Википедия

  • List of Unix utilities — This is a list of UNIX utilities as specified by IEEE Std 1003.1 2008, which is part of the Single UNIX Specification (SUS). These utilities can be found on UNIX Operating systems and most UNIX like operating systems. List IEEE Std 1003.1 2008… …   Wikipedia

  • Touch (Unix) — touch is a standard Unix program used to change a file s access and modification timestamps. It is also used to create a new empty file. History A touch utility appeared in Version 7 AT T UNIX. The version of touch bundled in GNU coreutils was… …   Wikipedia

  • Find — The find program is a directory search utility on Unix like platforms. It searches through one or more directory trees of a filesystem, locating files based on some user specified criteria. By default, find returns all files below the current… …   Wikipedia

  • Rm (Unix) — rm (short for remove ) is a Unix command used to delete files from a filesystem. Options Common options that rm accepts include:* r, which removes directories, removing the contents recursively beforehand (so as not to leave files without a… …   Wikipedia

  • Terrorism in the United Kingdom — Terrorism in the United Kingdom, according to the Home Office, poses a significant threat to the state. [http://www.homeoffice.gov.uk/security/terrorism and the law/terrorism act/proscribed groups List of proscribed terrorist groups] Home Office… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”