如何在Bash脚本中实现多道选择题训练测试功能?
Bash选择题训练脚本语法问题修复
问题说明
我要写一个用于选择题训练的简单Bash脚本,需求是依次展示题目、四个选项(a、b、c、d),接收用户输入后判断对错,接着继续下一题。单题功能已经跑通,但加第二题后出现语法错误。
可正常运行的单题代码
#!/usr/bin/bash echo Question1="How much is 2+2?" echo a="1" echo b="2" echo c="3" echo d="4" read Question1 if [ "$Question1" = "d" ]; then echo "this is correct" else echo "this is NOT correct" fi
添加第二题后出错的代码
#!/usr/bin/bash echo Question1="How much is 2+2?" echo a="1" echo b="2" echo c="3" echo d="4" read Question1 if [ "$Question1" = "d" ]; then echo "this is correct" else echo "this is NOT correct" echo Question2="How much is 2+1?" echo a="1" echo b="2" echo c="3" echo d="4" read Question2 if [ "$Question2" = "c" ]; then echo "this is correct" else echo "this is NOT correct" fi
错误原因
第一个if-else语句的else分支执行完后,没加fi来闭合整个if结构,导致后面的第二题代码被错误归到第一个if的逻辑块里,触发语法解析错误。
修复后的代码
#!/usr/bin/bash # 第一题 echo "Question1: How much is 2+2?" echo "a=1" echo "b=2" echo "c=3" echo "d=4" read Question1 if [ "$Question1" = "d" ]; then echo "this is correct" else echo "this is NOT correct" fi # 补上闭合第一个if的fi # 第二题 echo "Question2: How much is 2+1?" echo "a=1" echo "b=2" echo "c=3" echo "d=4" read Question2 if [ "$Question2" = "c" ]; then echo "this is correct" else echo "this is NOT correct" fi
额外优化建议
- 调整输出格式,让题目和选项更清晰易读
- 把出题逻辑封装成函数,避免重复写相同代码,示例如下:
#!/usr/bin/bash # 定义出题函数 ask_question() { local question="$1" local opt_a="$2" local opt_b="$3" local opt_c="$4" local opt_d="$5" local correct_ans="$6" echo -e "\n$question" echo "a) $opt_a" echo "b) $opt_b" echo "c) $opt_c" echo "d) $opt_d" read -p "请输入你的答案:" user_ans if [ "$user_ans" = "$correct_ans" ]; then echo "回答正确!" else echo "回答错误,正确答案是$correct_ans" fi } # 调用函数出题 ask_question "How much is 2+2?" "1" "2" "3" "4" "d" ask_question "How much is 2+1?" "1" "2" "3" "4" "c"
内容的提问来源于stack exchange,提问作者FDE
相关产品推荐
相关产品推荐

