我写了一个bash脚本,它通过用户输入获取计算数字。我遇到的问题是如果用户错误地键入了字母或空格,整个脚本都会失败,用户必须重新开始。
必须有一种简单的方法来检查输入是否仅为数字,如果意外输入了其他内容,将再次请求输入?
答案 0 :(得分:19)
使用while循环
number=""
while [[ ! $number =~ ^[0-9]+$ ]]; do
echo Please enter your age
read number
done
echo You are $number years old
答案 1 :(得分:8)
要避免繁重的正则表达式引擎,请使用简单的glob:
if [[ ! $input || $input = *[^0-9]* ]]; then
echo "Error: '$input' is not a number." >&2
fi
答案 2 :(得分:5)
在数字_33或33___之前和之后允许空格,但不允许3__3。而且没有信件。 0或
# -- get input until Correct
unset get_num
while [[ ! ${get_num} =~ ^[0-9]+$ ]]; do
echo "Please enter in a number:"
read get_num
done
echo This is a number : ${get_num}
# -- get input until Correct (within range)
unset get_num
while [[ ! ${get_num} =~ ^[0-9]+$ ]]; do
echo "Please enter in a number within range of (1-30):"
read get_num
! [[ ${get_num} -ge 1 && ${get_num} -le 30 ]] && unset get_num
done
echo This is a number withn a range : ${get_num}
“由于正则表达式处理文本而不是数字,因此匹配给定范围内的数字需要额外注意。您不能只写[0-255]来匹配0到255之间的数字。有效的正则表达式,它匹配完全不同的东西。[0-255]是一个有三个元素的字符类:字符范围0-2,字符5和字符5(再次)。这个字符类匹配单个数字0,1 ,2或5,就像[0125]一样。“ 〜http://www.regular-expressions.info/numericranges.html
# -- get input until Correct (within range) (another way)
unset get_num
while [[ ! ${get_num} =~ ^([1-9]|1[0-9]|2[0-9]|30)$ ]]; do
echo "Please enter in a number within range of (1-30):"
read get_num
done
echo This is a number withn a range : ${get_num}
# -- get input, and check it only (no while loop)
unset get_num
echo "Please enter in a number:"
read get_num
if [[ ! ${get_num} =~ ^[0-9]+$ ]] ;then
echo "${get_num} isn't a number"
else
echo "${get_num} is a number"
fi