我只是不知道如何确保传递给脚本的参数是否为数字。

我只想这样做:

test *isnumber* $1 && VAR=$1 || echo "need a number"

有什么帮助吗?


当前回答

没有人建议bash的扩展模式匹配:

[[ $1 == ?(-)+([0-9]) ]] && echo "$1 is an integer"

或使用POSIX字符类:

[[ $1 == ?(-)+([[:digit:]]) ]] && echo "$1 is an integer"

其他回答

我找到了一个很短的版本:

function isnum()
{
    return `echo "$1" | awk -F"\n" '{print ($0 != $0+0)}'`
}
[[ $1 =~ ^-?[0-9]+$ ]] && echo "number"

别忘了——包括负数!

没有人建议bash的扩展模式匹配:

[[ $1 == ?(-)+([0-9]) ]] && echo "$1 is an integer"

或使用POSIX字符类:

[[ $1 == ?(-)+([[:digit:]]) ]] && echo "$1 is an integer"

我使用以下(整数):

## ##### constants
##
## __TRUE - true (0)
## __FALSE - false (1)
##
typeset -r __TRUE=0
typeset -r __FALSE=1

## --------------------------------------
## isNumber
## check if a value is an integer 
## usage: isNumber testValue 
## returns: ${__TRUE} - testValue is a number else not
##
function isNumber {
  typeset TESTVAR="$(echo "$1" | sed 's/[0-9]*//g' )"
  [ "${TESTVAR}"x = ""x ] && return ${__TRUE} || return ${__FALSE}
}

isNumber $1 
if [ $? -eq ${__TRUE} ] ; then
  print "is a number"
fi

跟进2013年10月David W的回答,如果使用expr,这可能会更好

test_var=`expr $am_i_numeric \* 0` >/dev/null 2>&1
if [ "$test_var" = "" ]
then
    ......

如果是数字,则乘以1将得到相同的值(包括负数)。否则,您将得到空值,您可以进行测试