Читать книгу Linux Bible - Christopher Negus - Страница 218

Telephone list

Оглавление

This idea has been handed down from generation to generation of old UNIX hacks. It's really quite simple, but it employs several of the concepts just introduced.

 #!/bin/bash # (@)/ph # A very simple telephone list # Type "ph new name number" to add to the list, or # just type "ph name" to get a phone number PHONELIST=~/.phonelist.txt # If no command line parameters ($#), there # is a problem, so ask what they're talking about. if [ $# -lt 1 ] ; then echo "Whose phone number did you want? " exit 1 fi # Did you want to add a new phone number? if [ $1 = "new" ] ; then shift echo $*>> $PHONELIST echo $* added to database exit 0 fi # Nope. But does the file have anything in it yet? # This might be our first time using it, after all. if [ ! -s $PHONELIST ] ; then echo "No names in the phone list yet! " exit 1 else grep -i -q "$*" $PHONELIST # Quietly search the file if [ $? -ne 0 ] ; then # Did we find anything? echo "Sorry, that name was not found in the phone list" exit 1 else grep -i "$*" $PHONELIST fi fi exit 0

So, if you created the telephone list file as ph in your current directory, you could type the following from the shell to try out your ph script:

 $ chmod 755 ph $ ./ph new "Mary Jones" 608-555-1212 Mary Jones 608-555-1212 added to database $ ./ph Mary Mary Jones 608-555-1212

The chmod command makes the ph script executable. The ./ph command runs the ph command from the current directory with the new option. This adds Mary Jones as the name and 608-555-1212 as the phone number to the database ($HOME/.phonelist.txt). The next ph command searches the database for the name Mary and displays the phone entry for Mary. If the script works, add it to a directory in your path (such as $HOME/bin).

Linux Bible

Подняться наверх