You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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"

关键修复说明

  1. 添加单词读取与打乱逻辑:通过while循环读取文件内容,过滤空行后存入数组,再用shuf命令随机打乱单词顺序。
  2. 修正循环条件:以数组长度${#shuffled_word_pairs[@]}作为循环上限,确保遍历所有单词对。
  3. 统一变量命名:使用total_questions和i+1标识问题序号,避免变量拼写混乱。
  4. 修复分数累加:用((score++))直接更新分数,确保计数正确。
  5. 处理空格问题:用xargs去除单词和输入内容的前后空格,避免因空格导致的匹配失败。

内容的提问来源于stack exchange,提问作者David Lindsay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:08:08