如何编写 Bash 脚本来显示菜单、接受用户输入和显示数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2033309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:51:00  来源:igfitidea点击:

How can I write a Bash Script to display a menu, accept user input and display data?

bash

提问by KK.

I want to write Bash Script with User Input for my assignment called "book store service". Firstly, it has option menu like "add new book name " "author name" "remove book" "update" "search" "show book list" "Exit". If I choice option 1, I've got to input new book's name. How could I write the user input and display output data when I choice "show book list" option. I've got trouble with this Assignment. Pls someone help me to clear about this, that would be really helpful and thankful to all of you.

我想为我的名为“书店服务”的作业编写带有用户输入的 Bash 脚本。首先,它有“添加新书名”“作者名”“删除书”“更新”“搜索”“显示书单”“退出”等选项菜单。如果我选择选项 1,我必须输入新书的名称。当我选择“显示书籍列表”选项时,如何编写用户输入并显示输出数据。我在这个作业上遇到了麻烦。请有人帮助我澄清这一点,这对你们所有人都非常有帮助和感谢。

回答by Paused until further notice.

Take a look at the selectstatement. It allows you to create a menu.

看看select声明。它允许您创建菜单。

PS3="Please choose an option "
select option in go stay wait quit
do
    case $option in
        go) 
            echo "Going";;
        stay|wait) 
            echo "Standing by";;
        quit)
            break;;
     esac
done

Which would look like:

看起来像:

1) go
2) stay
3) wait
4) quit
Please choose an option

Edit:

编辑:

One of your options might prompt for user input:

您的选项之一可能会提示用户输入:

read -rp "Enter a phrase: " phrase
echo "The phrase you entered was $phrase"

回答by dm76

You might want to check out Whiptailor Dialogwith which one can make graphical interfaces inside the terminal.

您可能想查看WhiptailDialog,用它们可以在终端内制作图形界面。

Hereand hereis a good resources on how to use whiptail.

这里这里是关于如何使用whiptail的很好的资源。

And the answers to thisquestion is a good example of how to use Dialog

这个问题的答案是如何使用 Dialog 的一个很好的例子

enter image description here

在此处输入图片说明

回答by Frank

Here is a code example that shows how to read user input: http://tldp.org/LDP/abs/html/internal.html#READR

这是一个代码示例,展示了如何读取用户输入:http: //tldp.org/LDP/abs/html/internal.html#READR

You can also use CLI arguments:

您还可以使用 CLI 参数:

test.sh

测试文件

echo 

CLI:

命令行界面:

$ ./test.sh testinput
testinput

回答by ghostdog74

you should check out this pageon how to use case/esac or select to create menus

您应该查看此页面,了解如何使用 case/esac 或选择创建菜单

Also, don't forget to start reading the whole document to learn about shell scripting

另外,不要忘记开始阅读整个文档以了解 shell 脚本