Bash脚本仅支持单次提问的逻辑错误排查求助
拼写测验脚本终止问题修复
问题根源
你的脚本仅执行第一个问题就终止,核心错误如下:
- 循环条件无效:初始
question=0,for ((i=0; i<$question; i++))的循环条件从一开始就不成立,若未提前给question赋值,循环根本无法正常遍历所有单词。 - 变量名拼写混乱:混用
question和questions变量,导致问题计数逻辑失效。 - 分数更新错误:
score=$((score++))的写法无法正确累加分数,后置自增在算术赋值中不会生效。 - 缺少单词文件读取逻辑:代码直接使用
shuffled_word_pairs数组,但未实现从单词文件读取数据并填充数组的步骤,导致数组内容不完整。
修复后的完整脚本
#!/bin/bash # 配置项 allow_multiple_attempts=true word_file="words.txt" # 替换为你的单词文件路径 # 读取单词文件并填充数组,过滤空行 shuffled_word_pairs=() while IFS= read -r line; do [[ -z "$line" ]] && continue shuffled_word_pairs+=("$line") done < "$word_file" # 打乱单词顺序 shuffled_word_pairs=($(shuf -e "${shuffled_word_pairs[@]}")) score=0 total_questions=${#shuffled_word_pairs[@]} start_time=$(date +%s) for ((i=0; i<total_questions; i++)); do current_pair=${shuffled_word_pairs[$i]} # 分割错误拼写与正确拼写,去除前后空格 misspelled_word=$(echo "$current_pair" | cut -d',' -f1 | xargs) correct_word=$(echo "$current_pair" | cut -d',' -f2 | xargs) if [[ -z "$misspelled_word" ]]; then continue fi echo "Question $((i+1)): What is the correct spelling of '$misspelled_word'?" read -p "Your answer: " answer answer=$(echo "$answer" | xargs) # 去除输入前后空格 while [[ "$answer" != "$correct_word" ]]; do if [[ "$answer" == "skip" ]]; then echo "Question skipped." break elif [[ "$answer" == "help"* ]]; then first_char=$(echo "$correct_word" | cut -c1) echo "Hint: The first letter of the correct word is '$first_char'." read -p "Your answer: " answer answer=$(echo "$answer" | xargs) elif [[ "$answer" == "many"* ]]; then echo "Incorrect. The correct answer is '$correct_word'." read -p "Your answer: " answer answer=$(echo "$answer" | xargs) elif [[ "$allow_multiple_attempts" == true ]]; then read -p "Incorrect. Please try again: " answer answer=$(echo "$answer" | xargs) else echo "Incorrect. The correct answer is '$correct_word'." break fi done if [[ "$answer" == "$correct_word" ]]; then echo "Correct! ($((score+1))/$total_questions)" ((score++)) fi done # 计算耗时并输出结果 end_time=$(date +%s) time_spent=$((end_time - start_time)) echo -e "\nYour score: $score out of $total_questions" echo "Your time: $time_spent seconds"
关键修复说明
- 添加单词读取与打乱逻辑:通过
while循环读取文件内容,过滤空行后存入数组,再用shuf命令随机打乱单词顺序。 - 修正循环条件:以数组长度
${#shuffled_word_pairs[@]}作为循环上限,确保遍历所有单词对。 - 统一变量命名:使用
total_questions和i+1标识问题序号,避免变量拼写混乱。 - 修复分数累加:用
((score++))直接更新分数,确保计数正确。 - 处理空格问题:用
xargs去除单词和输入内容的前后空格,避免因空格导致的匹配失败。
内容的提问来源于stack exchange,提问作者David Lindsay
相关产品推荐
相关产品推荐

