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

我只想这样做:

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

有什么帮助吗?


当前回答

Stack弹出了一条消息,问我是否真的想在回答30+后回答?但当然!!!使用bash新功能,如下所示:(在评论之后我做了更改)

函数isInt(){([[$1-eq$(($1+0))]]2>/dev/null&&[[$1!=“”]]&&echo 1)|| echo“”}

function isInt() {
   ([[ $1 =~ ^[-+0-9]+$  ]] && [[ $1 -eq $(( $1 + 0 )) ]] 2>/dev/null && [[ $1 != '' ]] && echo 1) || echo ''
}

支架:

===============out-of-the-box==================
 1. negative integers (true & arithmetic),
 2. positive integers (true & arithmetic),
 3. with quotation (true & arithmetic),
 4. without quotation (true & arithmetic),
 5. all of the above with mixed signs(!!!) (true & arithmetic),
 6. empty string (false & arithmetic),
 7. no value (false & arithmetic),
 8. alphanumeric (false & no arithmetic),
 9. mixed only signs (false & no arithmetic),
================problematic====================
 10. positive/negative floats with 1 decimal (true & NO arithmetic),
 11. positive/negative floats with 2 or more decimals (FALSE & NO arithmetic).

只有当与[[$(isInt<arg>)]]中的过程替换结合使用时,才能从函数中获得真/假,因为bash中没有逻辑类型,也没有函数的返回值。

当测试表达式的结果为“错误”时,我使用大写,反之亦然!

通过“算术”,我的意思是bash可以像以下表达式那样进行数学运算:$x=$(($y+34))。

当在数学表达式中,参数的行为与预期一致时,我使用“算术/无算术”;当参数与预期行为相比表现不佳时,我则使用“无算术”。

正如你所看到的,只有10和11是有问题的!

完美的

PS:请注意,最流行的答案在情况9中失败!

其他回答

[[ $1 =~ ^-?[0-9]+$ ]] && echo "number"

别忘了——包括负数!

几乎是你想要的语法。只需要一个函数编号:

#!/usr/bin/bash

isnumber(){
  num=$1
  if [ -z "${num##*[!0-9]*}" ]; 
    then return 1
  else
    return 0
  fi
}

$(isnumber $1) && VAR=$1 || echo "need a number";
echo "VAR is $VAR"

测试:

$ ./isnumtest 10
VAR is 10
$ ./isnumtest abc10
need a number
VAR is 

一种方法是使用正则表达式,如下所示:

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

如果值不一定是整数,请考虑适当地修改正则表达式;例如:

^[0-9]+([.][0-9]+)?$

…或,用符号处理数字:

^[+-]?[0-9]+([.][0-9]+)?$

以下解决方案也可以用于Bourne等基本shell,而不需要正则表达式。基本上,任何使用非数字的数值求值操作都会导致错误,在shell中,该错误将被隐式视为false:

"$var" -eq "$var"

如:

#!/bin/bash

var=a

if [ -n "$var" ] && [ "$var" -eq "$var" ] 2>/dev/null; then
  echo number
else
  echo not a number
fi

你也可以测试$?更明确的操作返回代码:

[ -n "$var" ] && [ "$var" -eq "$var" ] 2>/dev/null
if [ $? -ne 0 ]; then
   echo $var is not number
fi

标准错误的重定向是为了隐藏bash打印出的“预期整数表达式”消息,以防我们没有数字。

CAVETS(感谢以下评论):

带小数点的数字不被识别为有效的“数字”使用[[]]而不是[]将始终计算为true大多数非Bash shell始终将此表达式求值为trueBash中的行为没有记录,因此可能会在没有警告的情况下发生变化如果值在数字后面包含空格(例如“1 a”),则会产生错误,如bash:[[:1 a:表达式中的语法错误(错误标记为“a”)如果该值与var名称相同(例如i=“i”),则会产生错误,如bash:[[:i:expression递归级别超出(错误标记为“i”

老问题,但我只是想坚持我的解决方案。这一个不需要任何奇怪的外壳技巧,也不需要依赖于永远不存在的东西。

if [ -n "$(printf '%s\n' "$var" | sed 's/[0-9]//g')" ]; then
    echo 'is not numeric'
else
    echo 'is numeric'
fi

基本上,它只是从输入中删除所有数字,如果你留下一个非零长度的字符串,那么它就不是一个数字。