27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

exit $E_CHANGED_MIND<br />

;;<br />

*) echo "Deleting file \"$1\".";;<br />

esac<br />

find . −inum $inum −exec rm {} \;<br />

echo "File "\"$1"\" deleted!"<br />

exit 0<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

xargs<br />

See Example 12−22, Example 3−4, and Example 10−9 for scripts using find. Its manpage provides<br />

more detail on this complex and powerful command.<br />

A filter for feeding arguments to a command, and also a tool for assembling the commands<br />

themselves. It breaks a data stream into small enough chunks for filters and commands to process.<br />

Consider it as a powerful replacement for backquotes. In situations where backquotes fail with a too<br />

many arguments error, substituting xargs often works. Normally, xargs reads from stdin or from a<br />

pipe, but it can also be given the output of a file.<br />

The default command for xargs is echo. This means that input piped to xargs may have linefeeds and<br />

other whitespace characters stripped out.<br />

bash$ ls −l<br />

total 0<br />

−rw−rw−r−− 1 bozo bozo 0 Jan 29 23:58 file1<br />

−rw−rw−r−− 1 bozo bozo 0 Jan 29 23:58 file2<br />

bash$ ls −l | xargs<br />

total 0 −rw−rw−r−− 1 bozo bozo 0 Jan 29 23:58 file1 −rw−rw−r−− 1 bozo bozo 0 Jan 29 23:58<br />

ls | xargs −p −l gzip gzips every file in current directory, one at a time, prompting before<br />

each operation.<br />

An interesting xargs option is −n NN, which limits to NN the number of arguments<br />

passed.<br />

ls | xargs −n 8 echo lists the files in the current directory in 8 columns.<br />

Another useful option is −0, in combination with find −print0 or grep −lZ. This<br />

allows handling arguments containing whitespace or quotes.<br />

find / −type f −print0 | xargs −0 grep −liwZ GUI | xargs<br />

−0 rm −f<br />

grep −rliwZ GUI / | xargs −0 rm −f<br />

Either of the above will remove any file containing "GUI". (Thanks, S.C.)<br />

Example 12−4. Logfile using xargs to monitor system log<br />

Chapter 12. External Filters, Programs and Commands 153

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

Saved successfully!

Ooh no, something went wrong!