本文介绍了bash 脚本.只有在范围内时才接受整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有带有基本算术运算的 bash 脚本 - 加法、减法、除法和乘法.
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
如何使@num1 和@num2 的值仅在它们是特定范围内的数字时才被接受.例如 0 到 10.所以如果我输入 $num1 或 $num2 假设 500 会有消息输入有效值?
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?
推荐答案
您可以创建一个简单的函数来获取范围内的数字:
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
仅适用于整数.您也可以考虑在 case
命令之前输入数字以避免冗余代码.
Works for integers only. You might also consider inputting the numbers before the case
command to avoid redundant code.
这篇关于bash 脚本.只有在范围内时才接受整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!