我正在为一个类编写一个 bash 脚本,该类有一个主菜单和两个子菜单。我还没有完成我的脚本,但是我已经遇到了一个无法解决的问题:
我的脚本运行良好,但每次运行它时,都会收到以下错误(但我的代码仍按预期运行):
./menu1.sh: line 105: =: command not found
此外,当我进入另外两个子菜单时,我收到相同的错误(因为类似的代码):
./menu1.sh: line 7: e: command not found
./menu1.sh: line 79: r: command not found
导致错误的行是:until ($choice = q);
我使用它停留在每个单独的菜单上直到用户输入q
。
添加set -x
到我的代码中,+ = q
在打印错误之前显示。
在终端中输入which until
没有结果(它没有打印出任何路径)。
最后,输入echo $SHELL
prints/bin/bash
所以我使用 bash。
这是我的全部源代码(未完成):
#!/bin/bash
q=
cNum=
cNum1=
editSub () {
until ($choice = q); #ERROR OCCURS HERE
do
echo ""
echo "Edit Submenu:"
echo ""
echo "(a) Add a course"
echo "(d) Delete a course"
echo "(p) Display a course"
echo "(u) Update a course (status and/or grade)"
echo "(q) Return to Main Menu"
echo ""
echo -n "Enter choice: "
read choice
case $choice in
a)
echo -n "Course Number:"
read cNum
if (grep $cNum my_course)
then
echo "$cNum already exists!"
else
awk '/'$cNum'/ {printf $1$2 OFS $4 OFS $5 OFS $6 OFS $7 OFS $8" 0 N/A"}' courses.txt | cat >> my_course #THIS NEEDS WORK. clear the extra stuff and add integer credit value
fi
;;
d)
echo -n "Course Number: "
read cNum
if (grep $cNum my_course)
then
sed --in-place '/'$cNum'/d' my_course
echo "$cNum successfully deleted."
else
echo "Course does not exist."
fi
;;
p)
echo -n "Course Number: "
read cNum
if (grep $cNum my_course)
then
awk'/'$cNum'/ {printf "Course Number: "$1"'
#print the rest of the course info in a pretty format
else
echo "Course does not exist."
fi
;;
u)
echo -n "Course Number: "
read cNum
echo -n "Status: "
read status
echo -n "Grade: "
read grade
if (grep $cNum my_course)
then
date
#validate input for status and grade
#if status 0 or 1, change my_course to say so
#grade ABC, 1. N/A, 0.
#error message if invalid input
else
echo "Course does not exist."
fi
;; #FINISH THIS
q) return ;;
*) echo "Invalid choice.";;
esac
done
}
reportSub () {
until ($choice = q); #ERROR OCCURS HERE
do
echo ""
echo "Report Submenu:"
echo ""
echo "(a) Sort by course number"
echo "(p) Display all courses that you have taken"
echo "(g) Calculate the GPA"
echo "(q) Return to Main Menu"
echo ""
echo -n "Enter choice: "
read choice
case $choice in
a) sort -n my_course
;;
p) grep ' 1 ' my_course | sort
;;
g) date ;; #calculate GPA
q) return ;;
*) echo "Invalid choice.";;
esac
done
}
#main function
until ($choice = q); #ERROR OCCURS HERE
do
if [ -f my_course ]
then
echo ""
echo "Main Menu:"
echo ""
echo "(e) Edit Submenu"
echo "(r) Report Submenu"
echo "(q) Quit"
echo ""
echo -n "Enter choice: "
read choice
case $choice in
e) editSub ;;
r) reportSub ;;
q) exit ;;
*) echo "Invalid choice.";;
esac
else
>> my_course
fi
done
exit
答案1
until ($choice = q)
给出语法错误,因为括号导致命令$choice = q
在子 shell 环境中执行。
在 bash 中,你可以使用
until [[ $choice = q ]]
检查变量选择的值等于问。
有关详细信息,请参阅复合命令在男子猛击。
答案2
如果 $choice 可以为空,则应添加一个字符。如果 $choice 可以有空白字符,则应使用“”。
until [ "_$choice" = "_q" ]
do
done
并且不要忘记“[”之后和“]”之前的空格!