Berkeley-Sysadmin_DeCal - Lab3b
Berkeley-Sysadmin_DeCal - Lab3b
作者学习的版本为spring 2021,但近年的作业内容基本一致
Scpriting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# phonebook.sh
#!/bin/bash
flag=$1
case "$flag" in
new)
# check arg count
if [ $# -ne 3 ]; then
echo "Usage: $0 new name tel"
else
echo "$2 $3" >> phonebook.txt
fi
;;
list)
if [ ! -s phonebook.txt ]; then
echo "phonebook is empty"
else
cat phonebook.txt
fi
;;
lookup)
if [ $# -ne 2 ]; then
echo "Usage: $0 lookup name"
else
name=$2
# use grep to get matched name and its
# corresponding tel number
result=$(grep -i "^$name " phonebook.txt)
# use -z to check whether result is empty
if [ -z "$result" ]; then
echo "No entry found for $name"
else
echo "$result"
fi
fi
;;
remove)
if [ $# -ne 2 ]; then
echo "Usage: $0 remove name"
else
name=$2
if ! grep -iq "^$name " phonebook.txt; then
echo "No entry found for $name to remove"
else
# use sed to delete matched name
sed -i "/^$name /Id" phonebook.txt
echo "Entry for $name removed"
fi
fi
;;
*)
# handle unexpected cases
echo "Unknown command: $1"
echo "Usage: $0 [new] [list] [lookup] [remove]"
;;
esac
This post is licensed under CC BY 4.0 by the author.