Bash script. Accept integer only if is from range

只谈情不闲聊 提交于 2019-12-25 02:33:03

问题


I have bash script with basic arithmetic operations - Addition, Subtraction, Division and Multiplication.

    #! 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

How to make that values for @num1 and @num2 are accepted only if they are numbers in certain range. For example 0 to 10. So if I enter for $num1 or $num2 lets say 500 there will be message to enter valid value?


回答1:


You can create a simple function to get a number in range:

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

Works for integers only. You might also consider inputting the numbers before the case command to avoid redundant code.



来源:https://stackoverflow.com/questions/50220152/bash-script-accept-integer-only-if-is-from-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!