-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_db
More file actions
112 lines (94 loc) · 2.55 KB
/
simple_db
File metadata and controls
112 lines (94 loc) · 2.55 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/bin/bash
# CS 265 Assignment 2
# Man Yi (Ariel) Yeung
while true
do
echo -n "% "
read "input1"
case "$input1" in
quit) #quit command
exit
;;
setdb*) #setdb command
db="${input1:6}"
multfile=0
if [[ ! -z $(echo "$db" | grep " ") ]] #multiple filenames provided
then
db="${db% *}"
multfile=1
fi
if [[ -f "$db" ]]
then
if [[ -r "$db" ]]
then
echo "Database set to ${db}." #db exists and readable
database=$db
else
echo "File ${db} is not readable." #db exists but not readable
fi
else
touch "$db"
echo "File ${db} created. Database set to ${db}." #db not exist
database=$db
fi
if [[ $multfile == 1 ]]
then
echo "Extra arguments ignored." #print statement for multiple filename
fi
;;
add*) #add command
if [[ $(echo "$input1" | awk '{ print NF }') == 3 ]]
then
if [[ ! -z $database ]] #if database has been set
then
product=$(echo "$input1" | awk '{ print $2 }')
price=$(echo "$input1" | awk '{ print $3 }')
if [[ -z $(cat $database | grep $product) ]]
then
echo "$product:$price" >> $database #if product not present
echo "$product:$price has been added to the database."
else #if product present
cat $database | awk -F":" -v var1="$product" -v var2="$price" '$1~var1{gsub($2,var2)}1' > temp.txt && mv -f temp.txt $database
rm -f temp.txt
echo "$product has been updated to $price."
fi
else
echo "Database has not been set."
fi
else
echo "Incorrect syntax."
fi
;;
delete*) #delete command
if [[ $(echo "$input1" | awk '{ print NF }') == 2 ]]
then
delprod=$(echo "$input1" | awk '{ print $2 }')
if [[ ! -z $database ]]
then
if [[ ! -z $(cat $database | grep $delprod) ]]
then
sed -i "/$delprod/d" $database #database set and product found
echo "$delprod has been deleted from $database"
else
echo "$delprod does not exist in $database" #database set and product not found
fi
else
echo "Database has not been set." #database not set
fi
else
echo "Incorrect syntax."
fi
;;
printdb)
if [[ ! -z $database ]]
then
cat $database
else
echo "Database has not been set."
fi
;;
*) #Other commands
echo "Unrecognized command."
;;
esac
done