I wrote a simple address book in sh as an introduction to sh for people new to programming or shell scripting
Usage looks like this:
$ addressbook add
Enter data:
Some Person, Ph: 0412 345 678
Entry added
$ addressbook search person
Some Person, Ph: 0412 345 678
$
Code follows.
#!/usr/bin/env sh
DB_FILE=~/.addressbook.db
usage() {
echo "Usage: `basename $0` "
}
# must be at least one argument
if [ $# -eq 0 ]; then
usage
exit 1
fi
case "$1" in
"add")
# must be exactly one argument
if [ $# -ne 1 ]; then
usage
exit 1
fi
echo "Please enter name and number details on a single line, like 'Bob Rock, Mob: 0412 345 678'"
read input
# Write content to DB file
echo $input >> $DB_FILE
echo "Entry added"
;;
"search")
# Does the database exist?
if [ ! -e $DB_FILE ]; then
echo "Database doesn't exist. Please add some content first."
exit 1
fi
# If a search term wasn't specified on the command line, ask for one
if [ $# -eq 1 ]; then
echo "Enter a name: "
read searchterm
# The search term should be a single argument
elif [ $# -ne 2 ]; then
echo "Too many arguments."
usage
exit 1
else
searchterm=$2
fi
# Search the DB file for the specified string
grep -i "$searchterm" $DB_FILE | sort
if [ $? -ne 0 ]; then
echo "No results found."
fi
;;
*)
echo "Unknown argument $1"
usage
exit 1
;;
esac
Comments
GUI version
Here is a GUI version (requires kdebase)
#!/usr/bin/env sh
DB_FILE=~/.addressbook.db
if [ "`which kdialog`" = "" ]; then
echo "kdialog not found. Please make sure kdebase is installed."
exit 1
fi
RESULT=`kdialog --title "Choose operation" --menu "Select an operation:" add "Add an entry" search "Search database"`
RETVAL=$?
if [ $RETVAL -eq 1 ]; then
exit
elif [ $RETVAL -ne 0 ]; then
exit $RETVAL
fi
case "$RESULT" in
"add")
# Ask for input to add to the DB
RESULT=`kdialog --title "Enter the entry" --inputbox "Enter an entry":`
RETVAL=$?
if [ $RETVAL -eq 1 ]; then
exit
elif [ $RETVAL -ne 0 ]; then
exit $RETVAL
fi
# Write content to DB file
echo "$RESULT" >> $DB_FILE
kdialog --title "Added" --msgbox "Entry added"
;;
"search")
RESULT=`kdialog --title "Enter search terms" --inputbox "Enter search terms":`
RETVAL=$?
if [ $RETVAL -eq 1 ]; then
exit
elif [ $RETVAL -ne 0 ]; then
exit $RETVAL
fi
TMPFILE=$(mktemp)
grep -i "$RESULT" $DB_FILE > $TMPFILE
kdialog --textbox $TMPFILE 600 400
rm $TMPFILE
;;
*)
echo "Unknown argument $RESULT"
usage
exit 1
;;
esac
--
Darren