首页 > 解决方案 > 当做出无效选择时让菜单循环 BASH

问题描述

嘿伙计们,所以我试图让这个菜单在 case 语句中做出无效选择时循环,但很难弄清楚我应该在我的 while 循环中回调什么我尝试使用 * 因为这是在case 作为无效的选择,但是当它看到它时它需要一个操作数,所以我不确定如何在下面调用它是代码,非常感谢任何帮助。

#Main menu.
#Displays a greeting and waits 8 seconds before clearing the screen

echo "Hello and welcome to the group 97 project we hope you enjoy using our program!"

sleep 8s
clear

while [[ $option -eq "*" ]]
do
    #Displays a list of options for the user to choose.

    echo "Please select one of the folowing options."
    echo -e "\t0. Exit program"
    echo -e "\t1. Find the even multiples of any number."
    echo -e "\t2. Find the terms of any linear sequence given the rule Un=an+b."
    echo -e "\t2. Find the numbers that can be expressed as the product of two nonnegative integers in succession and print  them in increasing order."

    #Reads the option selection from user and checks it against case for what to do.

    read -n 1 option

    case $option in
        0)
            exit ;;
        1)
            echo task1 ;;
        2)
            echo task2 ;;
        3)
            echo task3 ;;
        *)
            clear
            echo "Invalid selection, please try again.";;
    esac
done

标签: bashscriptingmenucase

解决方案


不要重新发明内置select 命令

choices=(
    "Exit program"
    "Find the even multiples of any number."
    "Find the terms of any linear sequence given the rule Un=an+b."
    "Find the numbers that can be expressed as the product of two nonnegative integers in succession and print  them in increasing order."
)

PS3="Please select one of the options: "
select choice in "${choices[@]}"; do
    case $choice in
        "${choices[0]}") exit ;;
        "${choices[1]}")
            echo task1
            break ;;
        "${choices[2]}")
            echo task2
            break ;;
        "${choices[3]}")
            echo task3
            break ;;
    esac
done

如果您想留在菜单中直到“退出”,然后删除中断。


推荐阅读