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

我只想这样做:

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

有什么帮助吗?


当前回答

只是对“玛丽”的跟进。但因为我没有足够的代表,所以无法将此作为评论发布到该帖子中。无论如何,这是我使用的:

isnum() { awk -v a="$1" 'BEGIN {print (a == a + 0)}'; }

如果参数是数字,函数将返回“1”,否则将返回“0”。这对整数和浮点数都有效。用法如下:

n=-2.05e+07
res=`isnum "$n"`
if [ "$res" == "1" ]; then
     echo "$n is a number"
else
     echo "$n is not a number"
fi

其他回答

我对在shell中直接解析数字格式的解决方案感到惊讶。shell不太适合这一点,因为它是用于控制文件和进程的DSL。下面有很多解析器,例如:

isdecimal() {
  # filter octal/hex/ord()
  num=$(printf '%s' "$1" | sed "s/^0*\([1-9]\)/\1/; s/'/^/")

  test "$num" && printf '%f' "$num" >/dev/null 2>&1
}

将“%f”更改为所需的任何特定格式。

在这里用一个正则表达式来测试整个部分和小数部分,并用点分隔。

re="^[0-9]*[.]{0,1}[0-9]*$"

if [[ $1 =~ $re ]] 
then
   echo "is numeric"
else
  echo "Naahh, not numeric"
fi

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

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

没有抨击(即使在System V sh中也有效),

case $string in
    ''|*[!0-9]*) echo bad ;;
    *) echo good ;;
esac

这将拒绝空字符串和包含非数字的字符串,接受其他所有内容。

负数或浮点数需要一些额外的工作。一个想法是排除-/。在第一个“bad”模式中,添加更多包含不正确用法的“bad“模式(?*-*/*.*.*)

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

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

或使用POSIX字符类:

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