退出bash switch语句

Mos*_*ses 6 bash

我编写了一个菜单驱动的bash脚本,它使用循环switch case内部while来执行各种菜单选项.一切正常.现在我正在尝试通过对用户输入执行错误测试来改进程序,但我似乎无法使其工作......

问题是我不知道如何正确地突破switch语句,而不会打破while循环(这样用户可以再试一次).

# repeat command line indefinitely until user quits
while [ "$done" != "true" ]
do
   # display menu options to user
   echo "Command Menu" # I cut out the menu options for brevity....

   # prompt user to enter command
   echo "Please select a letter:"
   read option

   # switch case for menu commands, accept both upper and lower case
   case "$option" in

   # sample case statement
   a|A) echo "Choose a month"
        read monthVal
        if [ "$monthVal" -lt 13 ]
        then 
           cal "$monthVal"
        else
           break # THIS DOES NOT WORK. BREAKS WHILE LOOP, NOT SWITCH!
        fi
        ;;
   q|Q) done="true" #ends while loop
        ;;
   *)   echo "Invalid option, choose again..."
        ;;
   esac
done
exit 0
Run Code Online (Sandbox Code Playgroud)

当用户输入有效的月份值时程序工作正常,但如果他们输入的数字高于13,而不是打破switch语句并再次重复循环,程序会断开switch和while循环并停止运行.

Joh*_*ica 10

点击;;将终止案例陈述.尽量不做任何事情:

a|A) echo "Choose a month"
     read monthVal
     if [ "$monthVal" -lt 13 ]
     then 
        cal "$monthVal"
     fi
     ;;
Run Code Online (Sandbox Code Playgroud)

  • 这个问题是当我有多个`if`语句时,需要针对用户输入运行多个测试.即使第一个失败,编程逻辑仍将继续通过其他`if`语句,好像没有错. (2认同)

gle*_*man 6

将其主体移动case到一个函数中,您可以随意return使用该函数.

do_A_stuff() {
    echo "Choose a month"
    read monthVal
    if [ "$monthVal" -lt 13 ]
    then 
       cal "$monthVal"
    else
       return
    fi
    further tests ...
}
Run Code Online (Sandbox Code Playgroud)

然后

case $whatever in
a|A) do_A_stuff ;;
Run Code Online (Sandbox Code Playgroud)


Phi*_*hil 5

我认为您的意思break是“退出此case语句并重新启动while循环”。但是,case ... esac它不是控制流语句(尽管它可能闻起来像一个),并且没有注意break

尝试更改breakcontinue,它将控制权发送回while循环的开始。