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...

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

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

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

#!/bin/bash<br />

E_WRONG_DIRECTORY=73<br />

clear # Clear screen.<br />

TargetDirectory=/home/bozo/projects/GreatAmericanNovel<br />

cd $TargetDirectory<br />

echo "Deleting stale files in $TargetDirectory."<br />

if [ "$PWD" != "$TargetDirectory" ]<br />

then # Keep from wiping out wrong directory by accident.<br />

echo "Wrong directory!"<br />

echo "In $PWD, rather than $TargetDirectory!"<br />

echo "Bailing out!"<br />

exit $E_WRONG_DIRECTORY<br />

fi<br />

rm −rf *<br />

rm .[A−Za−z0−9]* # Delete dotfiles.<br />

# rm −f .[^.]* ..?* to remove filenames beginning with multiple dots.<br />

# (shopt −s dotglob; rm −f *) will also work.<br />

# Thanks, S.C. for pointing this out.<br />

# Filenames may contain all characters in the 0 − 255 range, except "/".<br />

# Deleting files beginning with weird characters is left as an exercise.<br />

# Various other operations here, as necessary.<br />

echo<br />

echo "Done."<br />

echo "Old files deleted in $TargetDirectory."<br />

echo<br />

exit 0<br />

$REPLY<br />

The default value when a variable is not supplied to read. Also applicable to select menus, but only<br />

supplies the item number of the variable chosen, not the value of the variable itself.<br />

#!/bin/bash<br />

echo<br />

echo −n "What is your favorite vegetable? "<br />

read<br />

echo "Your favorite vegetable is $REPLY."<br />

# REPLY holds the value of last "read" if and only if<br />

# no variable supplied.<br />

echo<br />

echo −n "What is your favorite fruit? "<br />

read fruit<br />

echo "Your favorite fruit is $fruit."<br />

echo "but..."<br />

echo "Value of \$REPLY is still $REPLY."<br />

# $REPLY is still set to its previous value because<br />

# the variable $fruit absorbed the new "read" value.<br />

echo<br />

Chapter 9. Variables Revisited 69

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

Saved successfully!

Ooh no, something went wrong!