请求编写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 trueLoop: This keeps the script running until we explicitly break out of it (when the user enters 999). read -pfor 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
999triggers abreakto 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/elseblocks that cover all score ranges.
To use this script:
- Save it as
grade_checker.sh - Make it executable with
chmod +x grade_checker.sh - Run it with
./grade_checker.sh
内容的提问来源于stack exchange,提问作者Justin Siev
相关产品推荐
相关产品推荐

