在bash中创建子菜单

时间:2014-08-02 13:50:32

标签: bash shell submenu

我试图执行以下操作:

function main_menu 
{
option=0
until [ "$option" = "4" ]; do
echo "  1.) Add user"
echo "  2.) Remove user"
echo "  3.) Update user"
echo "  4.) Quit"

echo -n "Enter choice: "
read option
echo ""
case $option in
    1 ) add_user ; press_enter ;;
    2 ) remove_user ; press_enter ;;
    3 ) update_user ; press_enter ;;
    4 ) exit;;
    * ) tput setf 4;echo "Please enter 1, 2, 3, or 4";tput setf 4; 
esac
done
 }

在开关盒中(当选项不是4时)。第3个选项将显示另一个带开关盒的子菜单,如下所示:

function update_user 
{
 option=0
 until [ "$option" = "3"]; do
 echo "  1.) Update username"
 echo "  2.) Update password"
 echo "  3.) Return to menu"

 echo -n "Enter choice: "
 read option
 echo ""
 case $option in
 1 ) update_username; press_enter ;;
 2 ) update_password; press_enter ;;
 3 ) main_menu; press_enter ;;
 4 ) exit;;
 * ) tput setf 3;echo "Please enter 1, 2 or 3";tput setf 3; 
 esac
 done
  }

第3个选项返回主菜单,但是当我尝试退出时,子菜单会一直显示。

任何人都可以通过更好的方式为我提供建议吗?

2 个答案:

答案 0 :(得分:1)

$selection替换为$option,将break替换为exit,删除函数}中的update_user,函数{{1} } update_user之后添加}并将done替换为"$option" = "7"


#!/bin/bash

function update_user 
{
 option=0
 until [ "$option" = "3"]; do
 echo "  1.) Update username"
 echo "  2.) Update password"
 echo "  3.) Return to menu"

 echo -n "Enter choice: "
 read option
 echo ""
 case $option in
 1 ) update_username; press_enter ;;
 2 ) update_password; press_enter ;;
 3 ) main_menu; press_enter ;;
 4 ) break ;;
 * ) tput setf 3;echo "Please enter 1, 2 or 3";tput setf 3; 
 esac
#   }
 done
}

function main_menu 
{
option=0
until [ "$option" = "4" ]; do
echo "  1.) Add user"
echo "  2.) Remove user"
echo "  3.) Update user"
echo "  4.) Quit"

echo -n "Enter choice: "
read option
echo ""
case $option in
    1 ) add_user ; press_enter ;;
    2 ) remove_user ; press_enter ;;
    3 ) update_user ; press_enter ;;
    4 ) exit;;
    * ) tput setf 4;echo "Please enter 1, 2, 3, or 4";tput setf 4; 
esac
done
 }

main_menu

答案 1 :(得分:1)

正如@ KonstantinV.Salikhov所指出的,bash中的菜单是select循环的用途。

以下是使用select实现菜单的一种方式:

main_menu () {
    options=(
        "Add user"
        "Remove user"
        "Update user"
        "Quit"
    )
    select option in "${options[@]}"; do
        case $option in
            ${options[0]})
                add_user
                break
            ;;
            ${options[1]})
                remove_user
                break
            ;;
            ${options[2]})
                update_user
                break
             ;;
            ${options[3]})
                exit
             ;;
            *) 
                echo invalid option
            ;;
        esac
    done
}
main_menu