#!/bin/bash
#Output file save the students information
FILE=./zhubinqiang_v1.0
#temp file
TMP=./.tmp
#This is menu
menu () {
echo "***************************************************************************"
echo -e "\t\t1.Add a student information"
echo -e "\t\t2.Query a student information by ID"
echo -e "\t\t3.Delete a student information by ID"
echo -e "\t\t4.Screen clearing"
echo -e "\t\t0.Exit this program"
echo "***************************************************************************"
echo -n "Select:"
}
#Add a student infomation
add () {
#validate ID
while [ 1 ];do
echo -n "Student ID(001-999):"
read id
flag=`echo $id|grep -c "^[0-9]\{3\}$"`
if [ $flag -eq 0 -o "$id" == "000" ] ; then
echo "ID must 001-999"
continue
fi
flag2=`awk '{print $1}' $FILE | grep -c ^${id}$`
if [ $flag2 -ge 1 ] ;then
echo "The ID must be only one!"
continue
fi
break
done
#validate Name
while [ 1 ];do
echo -n "Student name(only a-z,A-Z and within 5 characters):"
read name
flag=`echo $name|grep -c "^[a-zA-Z]\{1,5\}$"`
if [ $flag -eq 0 ] ; then
echo "name must within 5 characters only a-z,A-Z"
else
#Name into the capital letters
name=`echo $name | tr '[a-z]' '[A-Z]'`
break
fi
done
#validate Sex
echo -n "Student sex(M or F,default is M):"
read sex
if [ "$sex" = "F" -o "$sex" = "f" ] ; then
sex=F
else
sex=M
fi
#validate Class
while [ 1 ]; do
echo -n "Student class(01-99 default is NULL):"
read class
if [ "$class" == "" ];then
class=NULL
break
fi
#Class match 00-99
flag=`echo $class|grep -c "^[0-9]\{2\}$"`
#check ?
if [ $flag -eq 0 -o "$class" == "00" ] ; then
echo "class must 01-99"
else
break
fi
done
echo -e "$id\t$name\t$sex\t$class" >> $FILE
}
#Query a student by ID
query () {
echo -n "Input the student ID:"
read id
if [ "$id" == "" ] ; then
echo -e "ID\tName\tSex\tClass"
cat $FILE
else
echo -e "ID\tName\tSex\tClass"
grep $id $FILE
if [ $? != 0 ]; then
echo "No student information!"
fi
fi
}
#Delete a student by ID
delete () {
echo -n "Input the student ID:"
read id
flag=`grep -n "$id" $FILE`
if [ "$flag" == "" -o "$id" == "" ]; then
echo "can't find ID=$id student"
return
fi
#get delete number
num=`awk '{print $1}' $FILE | grep -n "${id}" |sed 's/:.*//g'`
echo -e "ID\tName\tSex\tClass"
sed -n "${num}p" $FILE
echo -n "Are you sure delete id(Y or N):"
read sure
if [ "$sure" == "Y" -o "$sure" == "y" ] ; then
sed "${num}d" $FILE > $TMP
cat $TMP > $FILE
echo "Deleted successful"
fi
}
#exit program
quit () {
echo "Thank you Bye!"
exit
}
#Error info
error () {
echo "error input!"
}
#screen cleaning
cls () {
clear
}
#main
main () {
while [ 1 ] ; do
menu
read number
case $number in
1) add ;;
2) query ;;
3) delete ;;
4) cls ;;
0) quit ;;
*) error ;;
esac
done
}
main