用linux shell/ target=_blank class=infotextkey>shell脚本编写的通讯录,已实现了“增、删、查”功能,“改”功能比较复杂,暂未实现,有兴趣的朋友可以自己加入此功能。
#!/dev/bash
# Name of address book
BOOK="address-book.txt"
exit=0
add() {
# Ask the user for a name and assign to a variable
echo -n "Name of person: "
read name
# Ask the user for a phone number and assign to a variable
echo -n "Phone number: "
read phone
# Echo the answers and ask for confirmation
echo "Should I enter the values:"
echo -e "$name ; $phone n"
echo -n "y/n: "
read answer
if [ "$answer" == "y" ]
then
# Write the values to the address book
echo "$name ; $phone" >>$BOOK
else
# Give the user a message
echo "$name ; $phone NOT written to $BOOK"
fi
}
list() {
# Print the book with line numbers and paused with less
nl --number-separator=": " $BOOK | less
}
find() {
# Ask the user what to look for.
echo -n "What person or number are you seeking: "
read find
# Print the header before the answer
echo "Name ; Phone number"
grep -i $find $BOOK
}
del() {
# Ask the user which line to delete
echo -n "Which line should I delete: "
read number
# Rename the file before deleting
mv $BOOK boo.txt
# Add line numbers and delete against that number
nl --number-separator=":" boo.txt | grep -v $number: | awk -F: '{print $2}' | tee $BOOK
}
main() {
while [ $exit -ne 1 ]
do
echo "What operation do you want?"
echo -e "add, list, find, del, exit: "
read answer
if [ "$answer" = "add" ]
then
add
elif [ "$answer" = "list" ]
then
list
elif [ "$answer" = "find" ]
then
find
elif [ "$answer" = "del" ]
then
del
elif [ "$answer" = "exit" ]
then
exit=1
else
echo "I do not understand the command."
fi
done
exit 0
}
main