OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

xargs

The xargs command performs an interesting function. It accepts input from standard in- put and converts it into an argument list for a specified command. With our example, we would use it like this:


find ~ -type f -name 'foo*' -print | xargs ls -l

find ~ -type f -name 'foo*' -print | xargs ls -l


-rwxr-xr-x 1 me

-rw-r--r-- 1 me

-rwxr-xr-x 1 me

-rw-r--r-- 1 me


image

me 224 2007-10-29 18:44 /home/me/bin/foo

me 224 2007-10-29 18:44 /home/me/bin/foo

me

me

0 2016-09-19 12:53 /home/me/foo.txt

0 2016-09-19 12:53 /home/me/foo.txt

Here we see the output of the find command piped into xargs which, in turn, con- structs an argument list for the ls command and then executes it.


image

Note: While the number of arguments that can be placed into a command line is quite large, it’s not unlimited. It is possible to create commands that are too long for the shell to accept. When a command line exceeds the maximum length supported by the system, xargs executes the specified command with the maximum number of arguments possible and then repeats this process until standard input is ex- hausted. To see the maximum size of the command line, execute xargs with the

--show-limits option.


image


image

Dealing With Funny Filenames

Unix-like systems allow embedded spaces (and even newlines!) in filenames. This causes problems for programs like xargs that construct argument lists for other programs. An embedded space will be treated as a delimiter, and the result- ing command will interpret each space-separated word as a separate argument. To overcome this, find and xargs allow the optional use of a null character as ar- gument separator. A null character is defined in ASCII as the character repre- sented by the number zero (as opposed to, for example, the space character, which is defined in ASCII as the character represented by the number 32). The find command provides the action -print0, which produces null-separated output, and the xargs command has the --null option, which accepts null separated input. Here’s an example:

find ~ -iname '*.jpg' -print0 | xargs --null ls -l

Using this technique, we can ensure that all files, even those containing embedded spaces in their names, are handled correctly.


Top OS Cloud Computing at OnWorks: