这应该这样做:
#!/bin/bash
printf -v prompt '%s\n' "nhat and betah for each element" "TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)"
while read -p "$prompt" -a nbh; do
((${#nbh[@]}==4)) && break
echo "Wrong!!"
done
(我试图使脚本在良好实践方面更容易接受)。
现在你有一个问题:你将如何检查用户是否真的输入了数字?假设您有一个函数可以判断字符串是否是您接受的数字的有效表示。让我们调用这个函数banana
,因为它是一个好名字。然后:
#!/bin/bash
banana() {
# Like its name doesn't tell, this function
# determines whether a string is a valid representation
# of a number
# ...
# some wicked stuff here
# ...
}
printf -v prompt '%s\n' "nhat and betah for each element" "TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)"
good=0
while ((!good)) && read -p "$prompt" -a nbh; do
if ((${#nbh[@]}!=4)); then
echo "Wrong!! you must give 4 numbers! (and I can count!)"
continue
fi
for i in "${nbh[@]}"; do
if ! banana "$i"; then
echo "Your input \`$i' is not a valid number. It might be a valid banana, though. Check that with the local gorilla."
continue 2
fi
done
# If we're here, we passed all the tests. Yay!
good=1
done
# At this point, you should check that we exited the loop because everything was
# valid, and not because `read` has an error (e.g., the user pressed Ctrl-D)
if ((!good)); then
echo >&2 "There was an error reading your input. Maybe a banana jammed in the keyboard?"
exit 1
fi
# Here you're safe: you have 4 entries that all are valid numbers. Yay.
echo "Bravo, you just won a banana!"
现在,对于 function banana
,您可能想要使用正则表达式(但是我们会有两个问题,哦,亲爱的):
banana() {
[[ $1 =~ ^-?([[:digit:]]*\.?[[:digit:]]+|[[:digit:]]+\.?[[:digit:]]*)$ ]]
}
请注意,此处不支持科学形式,因此输入 like1e-6
将无法通过测试。如果你还需要处理这个,祝你好运,你自己一个人!
您还可以在脚本中添加一个复活节彩蛋:就在该while
行之后,添加:
[[ ${nbh[0],,} = gorilla ]] && { echo "banana"; continue; }
[[ ${nbh[0],,} = banana ]] && { echo "gorilla"; continue; }
干杯!