Bash脚本。仅当来自范围时才接受整数

时间:2018-05-07 18:11:47

标签: bash scripting

我有基本算术运算的bash脚本 - 加法,减法,除法和乘法。

    #! bin/bash

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)
            echo "Enter first no:"
            read num1
            echo "Enter second no:"
            read num2
            result=`expr $num1 + $num2`
            echo Answer: $result
            break
        ;;
        Subtraction)
            echo "Enter first no:"
            read num1
            echo "Enter second no:"
            read num2
            result=`expr $num1 - $num2`
            echo Answer: $result
            break
        ;;
        Multiplication)
            echo "Enter first no:"
            read num1
            echo "Enter second no:"
            read num2
            result=`expr $num1 * $num2`
            echo Answer: $result
            break
        ;;
        Division)
            echo "Enter first no:"
            read num1
            echo "Enter second no:"
            read num2
            result=$(expr "scale=2; $num1/$num2" | bc)
            echo Answer = $result
            break
        ;;
        *)
            echo Choose 1 to 4 only!!!!
            break
        ;;
    esac
    done

done

如果@ num1和@ num2的值是特定范围内的数字,则只接受这些值。例如0到10.因此,如果我输入$ num1或$ num2,可以说500将有消息输入有效值?

1 个答案:

答案 0 :(得分:2)

您可以创建一个简单的函数来获取范围内的数字:

get_number() {
    local lo=$1 up=$2 text=${3:-Enter a number: } num      
    shopt -s extglob

    until   
        read -p "$text" num
        [[ $num = ?(-)+([0-9]) ]] && (( $lo <= 10#$num && 10#$num <= $up ))
    do
        echo "Invalid input!" >&2
    done
    echo "$((10#$num))"
}

num1=$(get_number 10 15 "Enter first number: ")
num2=$(get_number -10 20) # use default prompt

仅适用于整数。您也可以考虑在case命令之前输入数字以避免冗余代码。