24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

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

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

9.7.2. Examples<br />

A shift statement is typically used when the number of arguments to a command is not known in advance, for<br />

instance when users can give as many arguments as they like. In such cases, the arguments are usually<br />

processed in a while loop with a test condition of (( $# )). This condition is true as long as the number of<br />

arguments is greater than zero. The $1 variable and the shift statement process each argument. The number of<br />

arguments is reduced each time shift is executed and eventually becomes zero, upon which the while loop<br />

exits.<br />

The example below, cleanup.sh, uses shift statements to process each file in the list generated by find:<br />

#!/bin/bash<br />

# This script can clean up files that were last accessed over 365 days ago.<br />

USAGE="Usage: $0 dir1 dir2 dir3 ... dirN"<br />

if [ "$#" == "0" ]; then<br />

echo "$USAGE"<br />

exit 1<br />

fi<br />

while (( "$#" )); do<br />

if [[ $(ls "$1") == "" ]]; then<br />

echo "Empty directory, nothing to be done."<br />

else<br />

find "$1" -type f -a -atime +365 -exec rm -i {} \;<br />

fi<br />

shift<br />

done<br />

-exec vs. xargs<br />

The above find command can be replaced with the following:<br />

find options | xargs [commands_to_execute_on_found_files]<br />

The xargs command builds and executes command lines from standard input. This has the advantage<br />

that the command line is filled until the system limit is reached. Only then will the command to execute<br />

be called, in the above example this would be rm. If there are more arguments, a new command line will<br />

be used, until that one is full or until there are no more arguments. The same thing using find -exec<br />

calls on the command to execute on the found files every time a file is found. Thus, using xargs greatly<br />

speeds up your scripts and the performance of your machine.<br />

In the next example, we modified the script from Section 8.2.4.4 so that it accepts multiple packages to install<br />

at once:<br />

#!/bin/bash<br />

if [ $# -lt 1 ]; then<br />

echo "Usage: $0 package(s)"<br />

exit 1<br />

fi<br />

while (($#)); do<br />

yum install "$1"

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

Saved successfully!

Ooh no, something went wrong!