跳转至

5. case

5.1 猜数字游戏

vim guess_num.sh
#!/bin/bash
read -p "please input a number:" num
case "$num" in
    1)
        echo "the number you input is $num"
        ;;
    [2-5])
        echo "the number you input is $num of [2-5]"
        ;;
    [6-9])
        echo "the number you input is $num of [6-9]"
        ;;
    *)
        echo "the number you input is not in [1-9]"
        exit 1;
esac

5.2 水果菜单脚本

vim fruit_menu.sh

#!/bin/bash
# 这些颜色的代码是在哪找到的来着???
RED='\E[1;31m'
GREEN='\E[1;32m'
YELLOW='\E[1;33m'
BLUE='\E[1;34m'
RES='\E[0m'

function usage(){
    echo "Usage: $0 {1|2|3}"
    exit 1
}

menu(){
    cat <<END
        1.apple
        2.banana
        3.orange
END
# 注意:这里的end必须顶头写!!!
}

choose(){
    read -p "please input the number you choose:" fruit
    case "$fruit" in
        1)
            echo -e "${RED}apple${RES}"
            ;;
        2)
            echo -e "${GREEN}banana${RES}"
            ;;
        3)
            echo -e "${YELLOW}orange${RES}"
            ;;
        *)
            usage
    esac
}

main(){
    menu
    choose
}

main

最后更新: 2022-02-19 13:59:07