我是一个新学习Bash脚本的学生,我在一道作业问题上遇到了困难。我想知道是否有一种简单的方法来确定用户输入的是整数还是其他类型的数据。更具体地说,如果提示用户输入一个整数,是否有快速检查的方法来验证?
一种方法是检查字符串中是否包含非数字字符。您可以将所有数字字符替换为空并检查长度--如果有长度,则存在非数字字符。
if [[ -n ${input//[0-9]/} ]]; then
echo "Contains letters!"
fi
另一种方法是在算术上下文中评估变量并检查它是否等于自身。这是特定于Bash的。
if [[ $((foo)) != $foo ]]; then
echo "Not just a number!"
fi
这有点不太正规,它使用了-eq来判断一个与其本意不同的东西,但是它检查了一个整数,如果没有找到整数,则返回一个错误和false的值,你可以将错误丢弃到/dev/null中。
read input
if [[ $input ]] && [ $input -eq $input 2>/dev/null ]
then
echo "$input is an integer"
else
echo "$input is not an integer or not defined"
fi
你可以使用正则表达式进行测试
if ! [[ "$yournumber" =~ ^[0-9]+$ ]] ;
then exec >&2; echo "error: Not a number"; exit 1
fi
expr $num + 1 2> /dev/null
if [ $? = 0 ]
then
echo "Val was numeric"
else
echo "Val was non-numeric"
fi
expr "$num" + 1 > /dev/null 2>&1
可以避免将 $num + 1
的值回显到标准输出。在 $num
周围加上引号是为了安全起见(例如,如果 $num
中有像 Foo Bar
这样的空格)。 - fbicknel #--- getRound -- Gives number rounded to nearest integer -----------------------
# usage: getRound <inputNumber>
#
# echos the rounded number
# Best to use it like:
# roundedNumber=`getRound $Number`
# check the return value ($?) and then process further
#
# Return Value:
# 2 - if <inputNumber> is not passed, or if more arguments are passed
# 3 - if <inputNumber> is not a positive number
# 0 - if <inputNumber> is successfully rounded
#
# Limitation: Cannot be used for negative numbers
#-------------------------------------------------------------------------------
getRound (){
if [ $# -ne 1 ]
then
exit 2
fi
#--- Check if input is a number
Input=$1
AB=`echo A${Input}B | tr -d [:digit:] | tr -d '.'`
if [ "${AB}" != "AB" ] #--- Allow only '.' and digit
then
exit 3
fi
DOTorNone=`echo ${Input} | tr -d [:digit:]` #--- Allow only one '.'
if [ "${DOTorNone}" != "" ] && [ "${DOTorNone}" != "." ]
then
exit 3
fi
echo $Input | awk '{print int($1+0.5)}' #--- Round to nearest integer
}
MyNumber=`getRound $1`
if [ $? -ne 0 ]
then
echo "Empty or invalid input passed"
else
echo "Rounded input: $MyNumber"
fi
这个对我有用,可以处理空输入的情况。
if [ $input -eq $input 2>/dev/null -o $input -eq 0 2>/dev/null ]
then
echo Integer
else
echo Not an integer
fi