正如它所说的那样。我正在尝试从书中的问题中编写一个简单的bash脚本。我正在尝试使用case语句,而且我可以告诉我正确使用它。但是我继续在\ r'案例$ i中获得“语法错误接近意外令牌'$'。
不知道为什么。我也确定我的代码中还有其他问题,因为这是我的第一个脚本。案例陈述在第10行。随意更正其他任何内容,最终程序将为学生成绩构建成绩数据文件,使用简单的awk脚本计算成绩的平均值,并将所有内容放在输出文件中。
function getStudentData () {
i=0
while [ $i<5 ]
do
case $i in
[0]) echo -n "Enter student name\n"
read name
;;
[1]) echo -n "Enter Quiz grade\n"
read quiz
checkLimits $quiz
;;
[2]) echo -n "Enter homework grade\n"
read hw
checkLimits $hw
;;
[3]) echo -n "Enter midterm grade\n"
read midterm
checkLimits $midterm
;;
[4]) echo -n "Enter Final grade \n"
read final
checkLimits $final
;;
esac
done
}
function checkLimits ($grade) {
if [ grade <= 100 || grade >= 0 ]; then
$i--
fi
}
if [ $# -lt 2 ]; then
echo "Incorrect number of arguments"
exit 1
fi
#Check awk existance
if [ ! -e $2 ]; then
echo "Error, .awk file does not exist"
exit 1
fi
#flag for data file existing, and awk file
flag=0
#Check for data file existing
if [ ! -e $1 ];then
flag=0
else
flag=1
fi
ans="yes"
while [ $ans == "yes" || $ans == "y" ]
do
echo "Do you want to enter a student record?"
read ans
if [ $ans == "y" || $ans == "yes" ];then
getStudentData
else
echo "we done"
exit 1
fi
done
答案 0 :(得分:1)
如果你把它写成循环,那么你应该写:
function getStudentData () {
i=0
while [[ $i < 5 ]]
do
case $i in
0) echo -n "Enter student name: "
read name
;;
1) echo -n "Enter Quiz grade: "
read quiz
checkLimits $quiz
;;
2) echo -n "Enter homework grade: "
read hw
checkLimits $hw
;;
3) echo -n "Enter midterm grade: "
read midterm
checkLimits $midterm
;;
4) echo -n "Enter Final grade: "
read final
checkLimits $final
;;
esac
done
}
function checkLimits() {
if [[ $1 -gt 100 || $1 -lt 0 ]]
then ((i--))
fi
}
这解决了许多问题:
echo -n
来压制换行符加\n
来添加换行符。checkLimits()
函数的语法。checkLimits()
函数中条件的语法。checkLimits()
函数中条件的反转逻辑。i
。它无法解决对全局变量$i
的依赖,这非常难看。
如果出现错误并且重新输入数据,循环的目的必须是返回。这是一个聪明的主意。不幸的是,你永远不会增加$i
,所以它不起作用。
以下是一些有效的代码:
function getStudentData () {
for ((i = 0; i < 5; i++))
do
case $i in
0) echo -n "Enter student name: "
read name
;;
1) echo -n "Enter Quiz grade: "
read quiz
checkLimits $quiz
;;
2) echo -n "Enter homework grade: "
read hw
checkLimits $hw
;;
3) echo -n "Enter midterm grade: "
read midterm
checkLimits $midterm
;;
4) echo -n "Enter Final grade: "
read final
checkLimits $final
;;
esac
done
}
function checkLimits() {
if [[ $1 -gt 100 || $1 -lt 0 ]]
then ((i--))
fi
}
getStudentData
echo "Name = $name"
echo "Quiz = $quiz"
echo "Homework = $hw"
echo "Midterm = $midterm"
echo "Final = $final"
示例运行的输出:
Enter student name: Eileen
Enter Quiz grade: 92
Enter homework grade: 94
Enter midterm grade: 95
Enter Final grade: 97
Name = Eileen
Quiz = 92
Homework = 94
Midterm = 95
Final = 97