如何在Linux Shell脚本中提示输入Yes/No/Cancel? [英] How do I prompt for Yes/No/Cancel input in a Linux shell script?

查看:951
本文介绍了如何在Linux Shell脚本中提示输入Yes/No/Cancel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在shell脚本中暂停输入,并提示用户选择.
标准YesNoCancel类型的问题.
如何在典型的bash提示符下完成此操作?

I want to pause input in a shell script, and prompt the user for choices.
The standard Yes, No, or Cancel type question.
How do I accomplish this in a typical bash prompt?

推荐答案

在shell提示符下获取用户输入的最简单,使用最广泛的方法是

The simplest and most widely available method to get user input at a shell prompt is the read command. The best way to illustrate its use is a simple demonstration:

while true; do
    read -p "Do you wish to install this program?" yn
    case $yn in
        [Yy]* ) make install; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

另一种方法,"> c4> 命令.这是使用select的相同示例:

Another method, pointed out by Steven Huwig, is Bash's select command. Here is the same example using select:

echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) make install; break;;
        No ) exit;;
    esac
done

使用select,您无需清理输入–它会显示可用的选项,然后键入与您的选项相对应的数字.它还会自动循环,因此如果输入无效的输入,则无需while true循环重试.

With select you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a while true loop to retry if they give invalid input.

此外,LéaGris 展示了一种使请求语言不可知的方法. ="https://stackoverflow.com/a/57739142/9084">她的答案.修改我的第一个示例以更好地服务于多种语言可能看起来像这样:

Also, Léa Gris demonstrated a way to make the request language agnostic in her answer. Adapting my first example to better serve multiple languages might look like this:

set -- $(locale LC_MESSAGES)
yesptrn="$1"; noptrn="$2"; yesword="$3"; noword="$4"

while true; do
    read -p "Install (${yesword} / ${noword})? " yn
    case $yn in
        ${yesptrn##^} ) make install; break;;
        ${noptrn##^} ) exit;;
        * ) echo "Answer ${yesword} / ${noword}.";;
    esac
done

很显然,此处没有翻译其他通信字符串(安装,回答),这需要通过更完整的翻译来解决,但在许多情况下,即使是部分翻译也将有所帮助.

Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.

最后,请通过优秀答案 /1765658/f-hauri> F.豪里(Hauri).

Finally, please check out the excellent answer by F. Hauri.

这篇关于如何在Linux Shell脚本中提示输入Yes/No/Cancel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆