當用戶輸入的值不是 y 或 Y 時,我想讓程式退出回圈
#! /bin/sh
#initialise variable continue as "y"
continue="y"
while [ $continue = "y" -o "Y" ] # condition to continue the repetition
do
echo "Please enter a station name to start search"
read name
result=`grep -w "^$name" STATIONS.TXT`
if [ -z "$result" ]; then # the input station is not in the file
echo "$name was not found in the file"
else # the input station is in the file
echo "$name was found in STATIONS.TXT"
fi
echo "Do you want to have another go? (enter y or Y to confirm, other to quit)"
read input
continue=$input
done
echo "End of the search program."
uj5u.com熱心網友回復:
您的條件非常接近它的外觀,只是運算子-o不適用于值,但適用于整個運算式。
正確的符號是:
while [ "$continue" = 'y' -o "$continue" = 'Y' ]
...或在標準中定義更好的變體(它適用于更多種類的 shell 實作):
while [ "$continue" = 'y' ] || [ "$continue" = 'Y' ]
...或者基于正則運算式的更通用的方式,它也允許匹配“是”和“是”:
while printf '%s' "$continue" | grep -q -x '[Yy]\(es\)\?'
(請注意,我已將引號的樣式更改為更安全的樣式。)
uj5u.com熱心網友回復:
使用while :; dowhile回圈(或while true; do-它們都歸零)。
然后立即在 之后read input,使用它來打破回圈:
case $input in [Yy]);; *) break;; esac
這將中斷回圈并完成程式,對于單個y或Y.
uj5u.com熱心網友回復:
要測驗Y或y,您可以使用
while [[ $continue == [yY] ]]
基本上,您可以在[[ ... == ... ]]命令的右側使用任何全域模式。
注意:此答案適用于 bash(或 zsh 或 ksh)。我提供了它,因為最初,這個問題被標記為bash。現在它變成了一個 POSIX-shell 問題,我的回答當然不再有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359451.html
