验证 bash 脚本中的输入
Validate input in bash script
我有一个代码可以通过给出宽度和高度来计算矩形的面积。
echo -n "Enter width: "
read width
echo -n "Enter height:"
read height
echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"
如何才能只输入数字,否则显示错误?
您或许可以使用 grep 进行检查,但如果您想要进行此类检查,bash(通常 shell)确实是一个糟糕的语言选择。
类似于:
echo $width | grep -E -q '^[0-9]+$' || echo "numeral expected!"
你可以这样做
if [[ -n "$width" ]] ; then
nodigits="$(echo $width| sed 's/[[:digit:]]//g')"
if [[ ! -z $nodigits ]] ; then
print "Invalid number format! Only digits, no commas, spaces, etc."
fi
fi
既然你读了两次输入,我会用一个函数来检查它。这样你就不会重复代码。
这会检查输入是否仅包含数字并且至少包含一位。否则,它会一直要求输入:
myread () {
while : # infinite loop
do
read value
[[ $value =~ ^[0-9]+$ ]] && echo "$value" && return #return value if good input
done
}
echo -n "Enter width: "
width=$(myread) #call to the funcion and store in $width
echo -n "Enter height: "
height=$(myread) #call to the funcion and store in $height
echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"
我有一个代码可以通过给出宽度和高度来计算矩形的面积。
echo -n "Enter width: "
read width
echo -n "Enter height:"
read height
echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"
如何才能只输入数字,否则显示错误?
您或许可以使用 grep 进行检查,但如果您想要进行此类检查,bash(通常 shell)确实是一个糟糕的语言选择。
类似于:
echo $width | grep -E -q '^[0-9]+$' || echo "numeral expected!"
你可以这样做
if [[ -n "$width" ]] ; then
nodigits="$(echo $width| sed 's/[[:digit:]]//g')"
if [[ ! -z $nodigits ]] ; then
print "Invalid number format! Only digits, no commas, spaces, etc."
fi
fi
既然你读了两次输入,我会用一个函数来检查它。这样你就不会重复代码。
这会检查输入是否仅包含数字并且至少包含一位。否则,它会一直要求输入:
myread () {
while : # infinite loop
do
read value
[[ $value =~ ^[0-9]+$ ]] && echo "$value" && return #return value if good input
done
}
echo -n "Enter width: "
width=$(myread) #call to the funcion and store in $width
echo -n "Enter height: "
height=$(myread) #call to the funcion and store in $height
echo "Area of rectangle $(echo "$height*$width" | bc) sqcm"