是否有一种简单的方法来确定用户输入是否是bash中的整数?

时间:2010-11-09 18:44:29

标签: bash shell

我是一名打击脚本的新生,我很难解决任务问题。 我想知道是否有一种简单的方法来确定用户的输入是否是整数。更具体地说,如果提示用户输入整数,是否需要快速检查以验证?

6 个答案:

答案 0 :(得分:27)

一种方法是检查它是否包含非数字字符。用任何东西替换所有数字字符并检查长度 - 如果长度有非数字字符。

if [[ -n ${input//[0-9]/} ]]; then
    echo "Contains letters!"
fi

另一种方法是检查在算术上下文中计算的变量是否等于自身。这是特定于bash的

if [[ $((foo)) != $foo ]]; then
    echo "Not just a number!"
fi

答案 1 :(得分:12)

这是一种kludge,它使用-eq来表示其他目的,但它检查一个整数,如果它没有找到一个int,它会返回一个错误,你可以抛到/ dev / null,值为false。

read input
if [ $input -eq $input 2>/dev/null ]
then
     echo "$input is an integer"
else
    echo "$input is not an integer"
fi

答案 2 :(得分:10)

您可以使用正则表达式进行测试

if ! [[ "$yournumber" =~ ^[0-9]+$ ]] ; 
 then exec >&2; echo "error: Not a number"; exit 1
fi

答案 3 :(得分:1)

我发现这篇帖子http://www.unix.com/shell-programming-scripting/21668-how-check-whether-string-number-not.html正在讨论这个问题。

如果你的输入不需要检查数字上是否有+/-,那么你可以这样做:

expr $num + 1 2> /dev/null
if [ $? = 0 ]
then
    echo "Val was numeric"
else
    echo "Val was non-numeric"
fi

答案 4 :(得分:1)

这是另一种方法。在大多数情况下,它可能比需要的更精细,但也会处理小数。我写了下面的代码来得到四舍五入的数字。它还会检查过程中的数字输入。

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

答案 5 :(得分:0)

这对我有用,处理空的输入案例。

if [ $input -eq $input 2>/dev/null -o $input -eq 0 2>/dev/null ]
then
   echo Integer
else
   echo Not an integer
fi
相关问题