逻辑错误可能

时间:2017-07-12 15:02:41

标签: bash loops while-loop

我自学bash

我该如何做到这一点?

有三个检查点......没有空行,没有特殊字符和 没有小于1且大于最大数字的数字

然而,在第三个检查站,如果你试图输入一个特殊角色,那么整个事情就会像卡片屋一样翻滚下来。

如何确保用户不输入空白行,没有特殊字符以及小于1且大于预定最大数字的数字?

读取-p"请输入行号:" LINE_NUMBER

# First checkpoint
# No blank lines accepted as input
while [[ -z "$line_number" ]] ;
do
echo
echo "Line number can not be blank."
echo
read -p "Please enter a valid line number? " line_number
echo
done

# Second checkpoint
# No special characters allowed as input
# Escaping the backtick or accent grave requires three back slashes before the backtick
while [[ $line_number == *['!'@#\$%^\&*()_+?~-\"\\\`]* ]] ; 
do
echo
echo "No special characters allowed"
echo
read -p "Please enter a valid line number? " line_number
echo
done

# Third checkpoint
# No number less than 1 and greater than the $total_line_number
while [[ $line_number -lt 1 || $line_number -gt $total_line_number ]] ; 
do
echo
echo -e "Line number can not be lesser than 1$ and bigger than              $total_line_number."
echo 
read -p "Please enter a number between the 1 and  $total_line_number scope? " line_number
echo
done

1 个答案:

答案 0 :(得分:3)

如果它应该是一个行号,则无需区分"常规"像a和"特殊"等字符像标点符号这样的字符。你唯一想接受的是数字:

line_number=
until [[ $line_number = +([[:digit:]]) &&
         $line_number -ge 1 &&
         $line_number -le $total_line_number  ]]; do
    read -p "Please enter a valid number between 1 and $total_line_number: " line_number
done