如题,下面是一个用linux shell脚本编写的通讯录,已实现了“增、删、查”功能,“改”功能比较复杂,待续~~
1 #!/dev/bash 2 3 # Name of address book 4 BOOK="address-book.txt" 5 6 exit=0 7 8 add() { 9 # Ask the user for a name and assign to a variable 10 echo -n "Name of person: " 11 read name 12 13 # Ask the user for a phone number and assign to a variable 14 echo -n "Phone number: " 15 read phone 16 17 # Echo the answers and ask for confirmation 18 echo "Should I enter the values:" 19 echo -e "$name ; $phone \n" 20 echo -n "y/n: " 21 read answer 22 23 if [ "$answer" == "y" ] 24 then 25 # Write the values to the address book 26 echo "$name ; $phone" >>$BOOK 27 else 28 # Give the user a message 29 echo "$name ; $phone NOT written to $BOOK" 30 fi 31 } 32 33 34 list() { 35 # Print the book with line numbers and paused with less 36 nl --number-separator=": " $BOOK | less 37 } 38 39 find() { 40 # Ask the user what to look for. 41 echo -n "What person or number are you seeking: " 42 read find 43 44 # Print the header before the answer 45 echo "Name ; Phone number" 46 grep -i $find $BOOK 47 } 48 49 del() { 50 # Ask the user which line to delete 51 echo -n "Which line should I delete: " 52 read number 53 54 # Rename the file before deleting 55 mv $BOOK boo.txt 56 57 # Add line numbers and delete against that number 58 nl --number-separator=":" boo.txt | grep -v $number: | awk -F: '{print $2}' | tee $BOOK 59 } 60 61 62 main() { 63 while [ $exit -ne 1 ] 64 do 65 echo "What operation do you want?" 66 echo -e "add, list, find, del, exit: " 67 read answer 68 69 if [ "$answer" = "add" ] 70 then 71 add 72 elif [ "$answer" = "list" ] 73 then 74 list 75 elif [ "$answer" = "find" ] 76 then 77 find 78 elif [ "$answer" = "del" ] 79 then 80 del 81 elif [ "$answer" = "exit" ] 82 then 83 exit=1 84 else 85 echo "I do not understand the command." 86 fi 87 done 88 exit 0 89 } 90 main