これは次のことを行う必要があります。
#!/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
、正規表現を使用することをお勧めします (しかし、そうすると 2 つの問題が発生します)。
banana() {
[[ $1 =~ ^-?([[:digit:]]*\.?[[:digit:]]+|[[:digit:]]+\.?[[:digit:]]*)$ ]]
}
ここでは科学形式がサポートされていないため、次のような入力1e-6
はテストに合格しないことに注意してください。これも処理する必要がある場合は、頑張ってください。
スクリプトにイースターエッグを追加することもできます。行の直後に次while
を追加します。
[[ ${nbh[0],,} = gorilla ]] && { echo "banana"; continue; }
[[ ${nbh[0],,} = banana ]] && { echo "gorilla"; continue; }
乾杯!