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

请求编写Bash WHILE循环成绩分级判定脚本

Bash Script for Continuous Grade Input & Grading

Hey Justin! You're absolutely right that a while loop is the way to go here—your initial code was on the right track, but we need to adjust it to handle continuous user input instead of just command-line arguments. Here's a complete, working script that meets your requirements, plus some extra input validation to avoid errors:

#!/bin/bash

# Continuous loop to prompt for grades until user enters 999
while true; do
    # Prompt user for input directly
    read -p "Please enter a grade (enter 999 to quit): " gr

    # Check if user wants to exit the program
    if [ "$gr" -eq 999 ]; then
        echo "Exiting now. Goodbye!"
        break
    fi

    # Validate input is a numeric value (prevents script errors)
    if ! [[ "$gr" =~ ^[0-9]+$ ]]; then
        echo "Oops, that's not a valid number. Please enter a numeric grade."
        continue
    fi

    # Determine and output the corresponding grade letter
    if [ "$gr" -ge 90 ]; then
        echo "A"
    elif [ "$gr" -ge 80 ]; then
        echo "B"
    elif [ "$gr" -ge 70 ]; then
        echo "C"
    else
        echo "Failed"
    fi
done

Key Adjustments & Breakdown:

  • Infinite while true Loop: This keeps the script running until we explicitly break out of it (when the user enters 999).
  • read -p for Direct Input: Replaces command-line argument handling with on-the-fly user prompts, so you don't need to pass grades when launching the script.
  • Clean Exit Condition: The check for 999 triggers a break to exit the loop gracefully with a friendly message.
  • Input Validation: The regex check [[ "$gr" =~ ^[0-9]+$ ]] ensures the user enters a valid number—no more weird errors from accidental letters or symbols!
  • Grade Logic: Your original grading rules are fully implemented with clear if/elif/else blocks that cover all score ranges.

To use this script:

  1. Save it as grade_checker.sh
  2. Make it executable with chmod +x grade_checker.sh
  3. Run it with ./grade_checker.sh

内容的提问来源于stack exchange,提问作者Justin Siev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:56:51