13.07.2015 Views

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

Linux System Administration Recipes A Problem-Solution Approach

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 8 ■ USING THE COMMAND LINE BETTER8-5. Using xargsxargs is an incredibly useful and powerful command. Basically, it takes a list of strings as input and thenexecutes your chosen command on every string in that list:xargs commandOften the input will be filenames, but they don’t have to be. It’s most commonly used to execute onecommand on the output from another command:command1 | xargs command2However, you can pipe any kind of input into it, and xargs will do its best to operate on that. Themost commonly used command from which xargs takes input is find.■ Note find has a built-in -exec option, but xargs is more efficient (because it operates on groups of filenamesrather than on each filename in turn as is the default case with find), and in general the syntax is also clearer toread on the command line.A couple of options that are useful for testing are -t, which echoes the command before executing it(so you can keep an eye on what’s happening and hit Ctrl-C if something is going wrong!), and -p, whichechoes it and asks for confirmation.find with xargsUse find to locate what you’re looking for (see the previous recipe), and use xargs to run the samecommand on each of the things found.Traditionally, an advantage to xargs was its ability to handle long command lines before failing,unlike some other commands. For example, the following command is intended to remove all tmp/*.mp3files (and ignore any subdirectories) but can fail with an “Argument list too long” message:rm `find tmp -maxdepth 1 -name '*.mp3'`The following alternative using xargs does the same thing but avoids the problem by batchingarguments:find tmp -maxdepth 1 -name '*.mp3' | xargs rmMore modern kernels (since 2.6.23) shouldn’t have this issue, but it’s wise to make your scripts asportable as possible, and the xargs version is also easier on the eye.The -n option allows you to manually batch arguments. This line will pass one argument at a timeto rm:find tmp -maxdepth 1 -name '*.mp3' -maxdepth 1 | xargs -n1 rm181Download at WoweBook.Com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!