该电话本可以实现以下功能
1.添加用户
2.查询用户
3.删除用户
4.展示用户
5.退出
代码展示:
#!/bin/bash
PHONEBOOK=phonebook.txt
function add_contact() {
echo "Adding new contact..."
read -p "Enter name: " name
read -p "Enter phone number: " number
echo "$name:$number" >> $PHONEBOOK
echo "Contact added successfully."
}
function search_contact() {
echo "Searching for contact..."
read -p "Enter name to search: " search_name
if grep -q "$search_name" $PHONEBOOK; then
grep "$search_name" $PHONEBOOK
else
echo "Contact not found."
fi
}
function list_contacts() {
echo "Listing all contacts..."
if [ -s "$PHONEBOOK" ]; then
cat $PHONEBOOK
else
echo "Phonebook is empty."
fi
}
function delete_contact() {
echo "Deleting contact..."
read -p "Enter name of contact to delete: " del_name
if grep -q "$del_name" $PHONEBOOK; then
sed -i "/$del_name/d" $PHONEBOOK
echo "Contact deleted successfully."
else
echo "Contact not found."
fi
}
function main_menu() {
echo "1. Add Contact"
echo "2. Search Contact"
echo "3. List Contacts"
echo "4. Delete Contact"
echo "5. Exit"
read -p "Enter your choice: " choice
case $choice in
add_contact
main_menu
;;
search_contact
main_menu
;;
list_contacts
main_menu
;;
delete_contact
main_menu
;;
echo "Exiting phonebook program."
exit 0
;;
*)
echo "Invalid choice."
main_menu
;;
esac
}
main_menu
应用展示: