我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
test *isnumber* $1 && VAR=$1 || echo "need a number"
有什么帮助吗?
我只是不知道如何确保传递给脚本的参数是否为数字。
我只想这样做:
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
其他回答
对于我的问题,我只需要确保用户不会意外地输入一些文本,因此我试图保持它简单易读
isNumber() {
(( $1 )) 2>/dev/null
}
根据手册页,这很符合我的要求
如果表达式的值为非零,则返回状态为0
为了防止“可能是数字”的字符串出现令人讨厌的错误消息,我忽略了错误输出
$ (( 2s ))
bash: ((: 2s: value too great for base (error token is "2s")
我对在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”更改为所需的任何特定格式。
我会这样做:
printf "%g" "$var" &> /dev/null
if [[ $? == 0 ]] ; then
echo "$var is a number."
else
echo "$var is not a number."
fi
注意:这将nan和inf识别为数字。
没有抨击(即使在System V sh中也有效),
case $string in
''|*[!0-9]*) echo bad ;;
*) echo good ;;
esac
这将拒绝空字符串和包含非数字的字符串,接受其他所有内容。
负数或浮点数需要一些额外的工作。一个想法是排除-/。在第一个“bad”模式中,添加更多包含不正确用法的“bad“模式(?*-*/*.*.*)
接受的答案在所有情况下都不适用于我,BASH 4+因此:
# -- is var an integer? --
# trim leading/trailing whitespace, then check for digits return 0 or 1
# Globals: None
# Arguments: string
# Returns: boolean
# --
is_int() {
str="$(echo -e "${1}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
case ${str} in ''|*[!0-9]*) return 1 ;; esac
return 0
}
如何使用它?
有效(将返回0=true):
is_int "100" && echo "return 0" || echo "return 1"
无效(将返回1=false):
is_int "100abc" && echo "returned 0" || echo "returned 1"
is_int "" && echo "returned 0" || echo "returned 1"
is_int "100 100" && echo "returned 0" || echo "returned 1"
is_int " " && echo "returned 0" || echo "returned 1"
is_int $NOT_SET_VAR && echo "returned 0" || echo "returned 1"
is_int "3.14" && echo "returned 0" || echo "returned 1"
输出:
returned 0
returned 1
returned 1
returned 1
returned 1
returned 1
returned 1
注意,在Bash中,1=假,0=真。我只是把它打印出来,而更可能是这样的:
if is_int ${total} ; then
# perform some action
fi