xargs is a command of the Unix and most Unix-like operating systems. It becomes useful when you want to pass a large amount of arguments to a command. In that case xargs will break the list of arguments in sublists large enough to be acceptable (the reader should note that you can't pass arbitrary long lists of parameters to a command GNU Core Utilities FAQ ).

For example commands like this:

rm /path/


  • or this

    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 the version below (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 in sublists and calls ''rm'' once for every sublist. Note that this is more efficient than the functionally equivalent version bellow:

    find /path -type f -exec rm '{}' \;

    ...which would call ''rm'' once for every single file.

    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

    References
    External links
  • GNU man page on xargs


  • Category:Unix software

    ru:Xargs