当用户输入不是 y 或 Y 的输入时,如何使 shell 程序退出?

How do I make the shell program exit when the user enters an input that is not y or Y?

我想让程序在用户输入的值不是 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."

对 while 循环使用 while :; do(或 while true; do - 它们都 return 为零)。

然后在 read input 之后立即使用它来打破循环:

case $input in [Yy]);; *) break;; esac

这会打破循环,并完成程序,除了单个 yY

除了运算符 -o 不适用于值而是整个表达式之外,您的条件非常接近它的外观。

正确的表示法是:

while [ "$continue" = 'y' -o "$continue" = 'Y' ]

...或在标准中定义得更好的变体(它适用于更多种类的 shell 实现):

while [ "$continue" = 'y' ] || [ "$continue" = 'Y' ]

...或基于正则表达式的更通用的方式,允许匹配“yes”和“Yes”:

while printf '%s' "$continue" | grep -q -x '[Yy]\(es\)\?'

(请注意,我已将引号的样式更改为更安全的样式。)

要测试 Yy,您可以使用

while [[ $continue == [yY] ]]

基本上,您可以在 [[ ... == ... ]] 命令的右侧使用任何全局模式。

注意:此答案适用于 bash(或 zsh 或 ksh)。我提供了它,因为最初,问题被标记为 bash。现在变成了POSIX-shell问题,我的回答当然就失效了