shell之打印菜单方法实例

狂风中的少年 提交于 2020-03-11 16:50:49

方法1

#!/bin/bash
#Author:mcsiberiawolf
#Time:2019-02-12 11:15:49
#Name:menu.sh
#Version:V1.0
#Description: This is a test script.

RETVAR=0
# 定义脚本路径
path=/server/scripts

# 如果路径不存在就创建
[ -d "$path" ] && mkdir -p $path

# 定义帮助函数
function Usage(){
    echo "Usage:$0 argv"
    return 1
}

# 定义安装服务函数
function InstallService(){
    if [ $# -ne 1 ]; then
        Usage
    fi
    local RETVAR=0
    echo "start installing ${1}."

    sleep 2

    if [ ! -x "$path/${1}.sh" ]; then
        echo "$path/${1}.sh does not exist or can not be exec."
        return 1
    else
        $path/${1}.sh 
        return $RETVAR
    fi
}

# 定义主函数
function main(){
    # 菜单提示
    PS3="`echo Pls input the num you want:`"
    # select 循环,菜单内容列表,列表中有空格加引号    
    select var in "Install lamp" "install lnmp" "exit"
    do
        case "$var" in
            "Install lamp")
                InstallService lamp
                RETVAR=$?
                ;;
            "Install lnmp")
                InstallService lamp
                RETVAR=$?
                ;;
            exit)
                echo bye.
                return 3
                ;;
            *)
                echo "The num you input must be {1|2|3}"
                echo "Input ERROR"
        esac
    done
    exit $RETVAR
}

main

方法2

#!/bin/bash
#Author:mcsiberiawolf
#Time:2019-02-12 11:15:49
#Name:menu.sh
#Version:V1.0
#Description: This is a test script.

RETVAR=0
path=/server/scripts

[ -d "$path" ] && mkdir -p $path

function Usage(){
    echo "Usage:$0 argv"
    return 1
}

function InstallService(){
    if [ $# -ne 1 ]; then
        Usage
    fi
    local RETVAR=0
    echo "start installing ${1}."

    sleep 2

    if [ ! -x "$path/${1}.sh" ]; then
        echo "$path/${1}.sh does not exist or can not be exec."
        return 1
    else
        $path/${1}.sh 
        return $RETVAR
    fi
}

function main(){
    PS3="`echo Pls input the num you want:`"
    select var in "Install lamp" "install lnmp" "exit"
    do
        case "$REPLY" in
            1)
                InstallService lamp
                RETVAR=$?
                ;;
            2)
                InstallService lamp
                RETVAR=$?
                ;;
            3)
                echo bye.
                return 3
                ;;
            *)
                echo "The num you input must be {1|2|3}"
                echo "Input ERROR"
        esac
    done
    exit $RETVAR
}

main
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!