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

求助:修改Bash四则运算脚本使其仅接受指定范围整数输入

Bash Arithmetic Script with Input Range Validation

Got it, let's tweak your existing arithmetic script so it only accepts integers within a specified range, plus we'll fix the division-by-zero issue that could crash the original code. Here's the updated version:

#!/bin/bash

# Function to get a valid integer within specified min/max range
get_valid_integer() {
    local prompt="$1"
    local min="$2"
    local max="$3"
    local input

    while true; do
        echo "$prompt"
        read input

        # Check if input is a positive integer
        if ! [[ "$input" =~ ^[0-9]+$ ]]; then
            echo "Error: Please enter a valid integer."
            continue
        fi

        # Check if input is within the specified range
        if (( input < min || input > max )); then
            echo "Error: Please enter a number between $min and $max."
            continue
        fi

        # If all checks pass, return the input
        echo "$input"
        break
    done
}

input="yes"
while [[ $input = "yes" ]]
do
    PS3="Press 1 for Addition, 2 for Subtraction, 3 for Multiplication and 4 for Division: "
    select math in Addition Subtraction Multiplication Division
    do
        case "$math" in
            Addition)
                num1=$(get_valid_integer "Enter first no:" 1 100)
                num2=$(get_valid_integer "Enter second no:" 1 100)
                result=$((num1 + num2))
                echo "Answer: $result"
                break
                ;;
            Subtraction)
                num1=$(get_valid_integer "Enter first no:" 1 100)
                num2=$(get_valid_integer "Enter second no:" 1 100)
                result=$((num1 - num2))
                echo "Answer: $result"
                break
                ;;
            Multiplication)
                num1=$(get_valid_integer "Enter first no:" 1 100)
                num2=$(get_valid_integer "Enter second no:" 1 100)
                result=$((num1 * num2))
                echo "Answer: $result"
                break
                ;;
            Division)
                num1=$(get_valid_integer "Enter first no:" 1 100)
                # For division, ensure divisor isn't zero (even if range allows it)
                while true; do
                    num2=$(get_valid_integer "Enter second no:" 1 100)
                    if (( num2 == 0 )); then
                        echo "Error: Cannot divide by zero. Please enter a non-zero number."
                    else
                        break
                    fi
                done
                result=$((num1 / num2))
                echo "Answer: $result"
                break
                ;;
            *)
                echo "Invalid option! Please select 1-4."
                ;;
        esac
    done
    echo "Do you want to continue? (yes/no)"
    read input
    # Validate continue input to avoid infinite loops from typos
    while [[ ! "$input" =~ ^(yes|no)$ ]]; do
        echo "Please enter either 'yes' or 'no'."
        read input
    done
done

Key Changes Explained:

  • Input Validation Function: The get_valid_integer function handles all the heavy lifting:
    • Checks if the input is a valid integer using a regular expression (^[0-9]+$).
    • Verifies the number falls between your specified min and max (I used 1-100 as an example—you can adjust these values in the function calls to fit your needs).
    • Loops until the user enters a valid input, so no more crashes from non-numeric entries.
  • Modern Arithmetic: Replaced the old expr command with Bash's built-in arithmetic expansion ($((...))) which is more efficient and cleaner.
  • Division-by-Zero Protection: Added an extra check for division to ensure the second number isn't zero, even though our range starts at 1—this is a safety net in case you adjust the range later to include 0.
  • Continue Input Validation: Added a check for the "continue" prompt to prevent infinite loops if the user types something other than "yes" or "no".

You can easily adjust the range by changing the min/max values in the get_valid_integer calls (e.g., get_valid_integer "Enter first no:" 0 500 to allow 0-500).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:03:48