Bash 脚本难度

Sel*_*mez 3 bash scripts

我正在创建一个 bash 脚本,我想创建一个菜单。当我运行代码时,它会显示菜单,但问题是当用户输入一个选项时,无论选择什么选项,它都会不断重新打印菜单以一次又一次地询问。

#!/bin/bash

declare -i choice=1;

while ((choice!=5))
    do
    echo "Main Menu:"
    echo -e "\t(a) Add"
    echo -e "\t(b) Remove"
    echo -e "\t(c) Seach"
    echo -e "\t(d) Display"
    echo -e "\t(e) Exit"
    echo -n "Please enter your choice:"
    read choice
    case $choice in
           "a"|"A")
            echo "You entered a"
            ;;
            "b"|"B")
            echo "You entered b"
            ;;
            "c"|"C")
            echo "You entered c"
            ;;
            "d"|"D")
            echo "You entered d"
            ;;
            "e"|"E")
            echo "You entered e"
            ((choice=5))
            ;;
            *)
            echo "invalid answer"
            ;;

    esac
done
Run Code Online (Sandbox Code Playgroud)

ter*_*don 5

无论何时调试某些东西,第一步都是让脚本打印它正在使用的各种变量。例如,在这里,如果在语句echo $choice 之前添加一个case,您将看到0无论您给它什么值,它都会打印。

这是因为您使用的是 (from )-i选项:declarehelp declare

  -i    to make NAMEs have the `integer' attribute
Run Code Online (Sandbox Code Playgroud)

因此,您将该变量声明为一个整数,然后向其传递字母(字符串),并且由于 bash 需要一个整数,因此将其转换为 0。

下一个问题是您正在运行一个while循环,该循环只会在$choiceis时退出5。即使你的其余语法没问题,那只会发生在 selection e

这是您的脚本的工作示例。我已经删除了declare不必要的。

#!/bin/bash

## Use another variable to exit the loop
ok=0;

while ((ok==0))
    do
    echo "Main Menu:"
    echo -e "\t(a) Add a contact"
    echo -e "\t(b) Remove a contact"
    echo -e "\t(c) Seach contacts"
    echo -e "\t(d) Display contacts"
    echo -e "\t(e) Exit"
    echo -n "Please enter your choice:"
    read choice
    case $choice in
        "a"|"A")
        ok=1
            ;;
        "b"|"B")
        ok=1
            ;;
        "c"|"C")
        ok=1
            ;;
        "d"|"D")
            ok=1
        ;;
        "e"|"E")
            exit
        ;;
            *)
            echo "invalid answer, please try again"
            ;;

    esac
done

echo "You entered $choice"
Run Code Online (Sandbox Code Playgroud)