lon*_*556 53 bash quoting regular-expression test
我试图检查一个输入是否是一个整数,我已经检查了它一百次,但没有看到这里的错误。唉,它不起作用,它会触发所有输入(数字/字母)的 if 语句
read scale
if ! [[ "$scale" =~ "^[0-9]+$" ]]
then
echo "Sorry integers only"
fi
Run Code Online (Sandbox Code Playgroud)
我玩过引号,但要么错过了它,要么什么也没做。我做错了什么?有没有更简单的方法来测试输入是否只是整数?
jim*_*mij 49
删除引号
if ! [[ "$scale" =~ ^[0-9]+$ ]]
then
echo "Sorry integers only"
fi
Run Code Online (Sandbox Code Playgroud)
cuo*_*glm 26
使用test命令的-eq操作符:
read scale
if ! [ "$scale" -eq "$scale" ] 2> /dev/null
then
echo "Sorry integers only"
fi
Run Code Online (Sandbox Code Playgroud)
它不仅适用于bash而且适用于任何 POSIX shell。来自 POSIX测试文档:
n1 -eq n2
True if the integers n1 and n2 are algebraically equal; otherwise, false.
Run Code Online (Sandbox Code Playgroud)
Tom*_*ale 14
由于 OP 似乎只想要正整数:
[ "$1" -ge 0 ] 2>/dev/null
Run Code Online (Sandbox Code Playgroud)
例子:
$ is_positive_int(){ [ "$1" -ge 0 ] 2>/dev/null && echo YES || echo no; }
$ is_positive_int word
no
$ is_positive_int 2.1
no
$ is_positive_int -3
no
$ is_positive_int 42
YES
Run Code Online (Sandbox Code Playgroud)
请注意,需要进行一次[测试:
$ [[ "word" -eq 0 ]] && echo word equals zero || echo nope
word equals zero
$ [ "word" -eq 0 ] && echo word equals zero || echo nope
-bash: [: word: integer expression expected
nope
Run Code Online (Sandbox Code Playgroud)
这是因为取消引用发生在[[:
$ word=other
$ other=3
$ [[ $word -eq 3 ]] && echo word equals other equals 3
word equals other equals 3
Run Code Online (Sandbox Code Playgroud)
小智 12
POSIX 和便携式解决方案是:
read scale
if [ -z "${scale##*[!0-9]*}" ];
then echo "Sorry integers only"
fi
Run Code Online (Sandbox Code Playgroud)
对于无符号整数,我使用:
read -r scale
[ -z "${scale//[0-9]}" ] && [ -n "$scale" ] || echo "Sorry integers only"
Run Code Online (Sandbox Code Playgroud)
测试:
$ ./test.sh
7
$ ./test.sh
777
$ ./test.sh
a
Sorry integers only
$ ./test.sh
""
Sorry integers only
$ ./test.sh
Sorry integers only
Run Code Online (Sandbox Code Playgroud)
( scale=${scale##*[!0-9]*}
: ${scale:?input must be an integer}
) || exit
Run Code Online (Sandbox Code Playgroud)
这会进行检查并输出您的错误。