检查用户输入是否存在bash脚本中的错误

时间:2013-10-30 15:38:45

标签: bash error-handling

请看下面的代码:

  echo "nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)"
  read -a nbh
  if [ ${#nbh[@]} -ne 4 ]
  then 
    echo "Wrong!! "
  fi

如果我忘记准确地给出4个元素,则此错误检查(如果循环)将终止程序。 是否有可能,而不是终止,再次给用户一次机会?即基本上再次转到read -a nbh行?

2 个答案:

答案 0 :(得分:2)

这应该做:

#!/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!"

现在,对于函数banana,您可能想要使用正则表达式(但是我们将遇到两个问题,哦,亲爱的):

banana() {
    [[ $1 =~ ^-?([[:digit:]]*\.?[[:digit:]]+|[[:digit:]]+\.?[[:digit:]]*)$ ]]
}

请注意,此处不支持科学表单,因此1e-6等输入不会通过测试。如果你还需要处理这个问题,祝你好运,你就是自己!

您还可以在脚本中添加复活节彩蛋:在while行之后添加:

[[ ${nbh[0],,} = gorilla ]] && { echo "banana"; continue; }
[[ ${nbh[0],,} = banana ]] && { echo "gorilla"; continue; }

干杯!

答案 1 :(得分:1)

while "this condition is not matched"可以成功:

#!/bin/bash

while [ ${#nbh[@]} -ne 4 ] <---- repeat until this is not true
do
  echo "nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)"
  read -a nbh
  if [ ${#nbh[@]} -ne 4 ]
  then 
    echo "Wrong!! "
  fi
done                       <---- finish while loop

测试

$ ./script
nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)
2 3
Wrong!! 
nhat and betah for each element 
        TIPS: 4 REAL NUMBER for each element(eg, 1.0 0.0 1.0 .1)
2 3 5 6
$