1

请查看以下代码:

  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再次上线?

4

2 回答 2

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

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

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

请注意,此处不支持科学形式,因此输入 like1e-6将无法通过测试。如果你还需要处理这个,祝你好运,你自己一个人!

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

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

干杯!

于 2013-10-30T15:54:29.170 回答
1

Awhile "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
$
于 2013-10-30T15:46:54.153 回答