创建菜单列表并执行任务

创建菜单列表并执行任务

我接到的任务是在 Linux 中创建一个菜单,但效果似乎并不理想。当我选择某项内容时,我希望能够执行该任务,然后在完成后返回主菜单。

#!/bin/bash

PS3='What do you want to do day: '
options=("Create Group" "Delete Group" "Create User 3" "Delete User" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Create Group")
            echo "You chose Create Group 1"
            ;;
        "Delete Group")
            echo "You chose to Delete Group"
            ;;
        "Create User")
            echo "You chose to Create User"
            ;;
        "Delete User")
            echo "You choose to Delete User"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

答案1

您可以使用 while 和永久 true 条件来执行此操作:

while [ 1 -eq 1 ]  # or while [ true ] ( as glenn said)
do
 select opt in "${options[@]}"
 do
 case $opt in
     "Create Group")
         echo "You chose Create Group 1"
         ;;
     "Delete Group")
         echo "You chose to Delete Group"
         ;;
     "Create User")
         echo "You chose to Create User"
         ;;
     "Delete User")
         echo "You choose to Delete User"
         ;;
     "Quit")
         break
         ;;
     *) echo invalid option;;
  esac
 done
done

答案2

我假设您想每次都显示菜单。尝试这个:

quit=false
until $quit; do
    select opt in "${options[@]}"; do
        case $opt in
            "Create Group")
                echo "You chose Create Group 1"
                break
                ;;
            "Delete Group")
                echo "You chose to Delete Group"
                break
                ;;
            "Create User")
                echo "You chose to Create User"
                break
                ;;
            "Delete User")
                echo "You choose to Delete User"
                break
                ;;
            "Quit")
                quit=true
                break
                ;;
            *) echo invalid option;;
        esac
    done
done

相关内容