Up to this point, we've been pretty focused on serious and important uses of shell scripts to improve your interaction with your Unix/Linux system and make the system more flexible and powerful. But there's another side to shell scripts that's worth exploring just briefly as the book wraps up, and that's games.
Don't worry ” I'm not proposing that we write a new version of The Sims as a shell script. It just turns out that there are a number of simple games that are easily and informatively written as shell scripts, and, heck, wouldn't you rather learn how to debug shell scripts by working with something fun than with some serious utility for suspending user accounts or analyzing Apache error logs?
Here are two quick examples up front to show you what I mean. First off, long-time Usenet readers know about something called rot13 , a simple mechanism whereby off- color jokes and obscene text are obscured to make them a bit less easily read. It's what's called a substitution cipher , and it turns out to be remarkably simple to accomplish in Unix.
To rot13 something, simply feed it through tr :
tr '[a-zA-Z]' '[n-za-mN-ZA-M]'
Here's an example:
$ echo "So two people walk into a bar..." tr '[a-zA-Z]' '[n-za-mN-ZA-M]' Fb gjb crbcyr jnyx vagb n one...
To unwrap it, simply apply the same transform:
$ echo 'Fb gjb crbcyr jnyx vagb n one...' tr '[a-zA-Z]' '[n-za-mN-ZA-M]' So two people walk into a bar...
Another short example is a palindrome checker. Type in something you believe is a palindrome , and it'll test it to see:
testit="$(echo $@ sed 's/[^[:alpha:]]//g' tr '[:upper:]' '[:lower:]')" backwards="$(echo $testit rev)" if [ "$testit" = "$backwards" ] ; then echo "$@ is a palindrome" else echo "$@ is not a palindrome" fi
The logic here: A palindrome is a word that's identical forward or backward, so the first step is to remove all nonalphabetic characters and then ensure that everything is lowercase. Then the Unix utility rev reverses the letters in a line of input. If the forward and backward versions are the same, we've got a palindrome, and if they differ , we don't.
The three short games presented in this final chapter are only a bit more complex, but all will prove fun and worth adding to your system, I'm sure. All three require separate data files, however, which you can most easily obtain from my website. For the word list, load and save the file at http://www.intuitive.com/ wicked /examples/long-words.txt , and for the state capitals data file download http://www.intuitive.com/wicked/examples/state.capitals.txt
Save both of the files in the directory /usr/lib/games/ for the scripts to work as written, or, if you save them elsewhere, modify the scripts to match.