【问题标题】:Bash script. Accept integer only if is from rangebash 脚本。仅当来自范围时才接受整数
【发布时间】:2018-05-07 18:11:47
【问题描述】:

我有带有基本算术运算的 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 会有消息输入有效值?

【问题讨论】:

  • 你试过什么?你应该能够想出一个测试,你可以用它来打破带有消息的 case 语句。这可能是一个很好的函数候选者。
  • 数字只是整数吗?
  • @PesaThe,是的。
  • while (( $num1 < 0 || $num1 > 10 )); do read -p'Number must be between 0 and 10.' num1; ... done
  • expr 是过时的 pre-POSIX 语法。使用result=$((num1 * num2)) 在现代兼容 POSIX 的 shell 中进行数学运算。 expr 语法需要分叉一个子shell,设置管道以读取该子shell 的输出,执行外部二进制文件,read()ing 其输出,wait()ing 收集其退出状态等;本机语法只是在内部对 bash 可执行文件进行数学运算。

标签: bash scripting


【解决方案1】:

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

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 命令之前输入数字以避免冗余代码。

【讨论】:

  • shopt -s extglob 是必需的。
  • @glennjackman 感谢您的提示。 extglob 是必需的吗?也许在旧版本中,但引用手册:...matched according to the rules described below in Pattern Matching, as if the extglob shell option were enabled..
  • 这种行为确实是版本相关的;更安全地启用标志以实现兼容性。
  • @CharlesDuffy 我明白了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 2016-03-13
  • 2016-01-04
  • 1970-01-01
相关资源
最近更新 更多